is_singular() not working if called via callback function of admin-ajax.php

An AJAX request is a new request to the server, and it is a request to admin-ajax.php. That is not a single post page. Any logic that depends on is_single() or any other page level template tags like it, won’t work. If your AJAX callback needs that sort of information you must pass it to that callback in your AJAX request– something like:

function my_enqueue($hook) {
    wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery'));
    if( is_single() ) {
      // in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
      wp_localize_script( 
    'ajax-script', 
    'ajax_object',
        array( 'is_single' => true ) 
      );
    }
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

Your ajax request would then include ajax_object.is_single as part of the query parameters as in this example from the Codex, which passed ajax_object.we_value through as whatever

jQuery(document).ready(function($) {
    var data = {
        action: 'my_action',
        whatever: ajax_object.we_value      // We pass php values differently!
    };
    // We can also pass the url value separately from ajaxurl for front end AJAX implementations
    jQuery.post(ajax_object.ajax_url, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

Your callback would then have access to the data via $_POST.

Leave a Comment