Ajax request in WordPress is always performed in admin side, so is_admin()
returns always true. If you need to know where the ajax request come from you need to check where the script is executed, not where the script send the ajax request.
For example:
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 );
}
Then, the js code (for my-script.js file in this example):
(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);