猿问

如何为未登录的用户加载 wp ajax?

我知道我应该按照文档说的wp_ajax_nopriv那样使用, 但我不确定如何使用。


在前端,我这样做:


var ajaxscript = { ajax_url : '<?php echo admin_url("admin-ajax.php"); ?>' };   

$.ajax({

  url: ajaxscript,

  type: 'post',

  dataType: 'json',

  data: { action: 'data_fetch', dates: datesSearch },

  success: function(data) {

    ...

  }

});

我知道我可以定义url的function,如:


  function myAjaxUrl() {

     echo '<script type="text/javascript">

             var ajaxurl = "' . admin_url('admin-ajax.php') . '";

           </script>';

  }

  add_action('wp_head', 'myAjaxUrl');

这将使前端的ajax调用如下:


$.ajax({

  url: ajaxurl...

但是wp_ajax_nopriv,为了能够访问wp-ajax未登录的用户,我将如何使用?


扬帆大鱼
浏览 147回答 2
2回答

交互式爱情

您需要做的只是将您的函数注册到一个名为 wp_ajax_nopriv_{your_function_name}所以,对于你的情况,add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' );应该做到这一点。在 WordPress 中注册一个 ajax 函数:1、在WordPress中注册一个ajax函数:可以在主题functions.php文件中添加这个。// Simple Ajax functionadd_action( 'wp_ajax_nopriv_simple_ajax_func', 'simple_ajax_func' );add_action( 'wp_ajax_simple_ajax_func', 'simple_ajax_func' );function simple_ajax_func() {&nbsp; echo json_encode(array('success' => true));&nbsp; wp_die();}2. 从 JavaScript 调用该 ajax 函数:var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';jQuery.ajax({&nbsp; url : ajax_url,&nbsp; type : 'post',&nbsp; data : {&nbsp; &nbsp; action : "simple_ajax_func",&nbsp; },&nbsp; success : function( response ) {&nbsp; &nbsp; console.log('Success');&nbsp; }});

达令说

你误解了 wp_ajax 动作。您必须使用 wp_ajax 过滤器在您的主题中创建一个 PHP 函数。add_action( 'wp_ajax_foobar', 'my_ajax_foobar_handler' );add_action( 'wp_ajax_nopriv_foobar', 'my_ajax_foobar_handler' );// This is the function that you will fire when your ajax code hits the admin_url('admin-ajax.php')function my_ajax_foobar_handler() {&nbsp; &nbsp;// Make your response and echo it.&nbsp; &nbsp;// Don't forget to stop execution afterward.&nbsp; &nbsp;wp_die();}因此,对于 WP admin ajax 了解需要触发此功能,您必须在您的 ajax 请求中传递它。//Note that the action here is what cames after the wp_ajax PHP functionvar my_php_ajax_action_name = 'foobar'$.ajax({&nbsp; url: ajaxurl,&nbsp; type: 'post',&nbsp; dataType: 'json',&nbsp; data: { action: my_php_ajax_action_name, dates: datesSearch },&nbsp; success: function(data) {&nbsp; &nbsp;// ...&nbsp; }});
随时随地看视频慕课网APP
我要回答