Wordpress中的Ajax请求总是在管理端执行,所以is_admin()
返回始终为true。如果需要知道ajax请求来自何处,则需要检查脚本的执行位置,而不是脚本发送ajax请求的位置。
例如:
add_action(\'wp_enqueue_scripts\', \'cyb_enqueue_scripts\');
function cyb_enqueue_scripts() {
//Register the script.
wp_register_script(\'my-script\', get_stylesheet_directory_uri(). \'/js/my-script.js\', array( \'jquery\' ) );
//Enqueue the script and dependencies
wp_enqueue_script(\'jquery\');
wp_enqueue_script(\'my-script\');
//Set up the vars data for the script
$scriptvars = array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
\'data\' => array(
\'action\' => \'get_something\',
\'is_admin\' => is_admin()
)
);
wp_localize_script(\'my-script\', \'script_vars\', $scriptvars);
}
add_action( \'wp_ajax_get_something\', \'get_something\');
add_action( \'wp_ajax_nopriv_get_something\', \'get_something\');
function get_something(){
if( isset($_POST[\'is_admin\']) && $_POST[\'is_admin\'] == true ) {
//The ajax request comes from admin area
$is_admin = true;
} else {
$is_admin = false;
}
$data = array( \'is_admin\' => $is_admin );
wp_send_json_success( $data );
}
然后,js代码(本例中的my-script.js文件):
(function($){
$(document).ready(function(){
jQuery.ajax({
url: script_vars.ajaxurl,
data: script_vars.data,
type: \'post\',
success: function(response){
alert(response.data.is_admin);
}
});
});
})(jQuery);