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

In my single.php I’ve some code like this …

if(is_singular('post')) {
   echo 'Blog';
} else {
   echo 'CPT';
} 

If I approach single.php from blog or CPT index page by using the_permalink(), this condition works correctly. It show ‘Blog’ when I open single blog post and shows ‘CPT’ when I open single CPT.

Read More

Now the issue is if approach single.php via some callback function of admin-ajax.php it always echos ‘CPT’ even if I click on single blog post link. My ajax callback function is something like this …

    function ajax_callback() {

        get_template_part( 'single', 'portfolio' );

        die(); // to avoide 0 at the end

    }
    add_action('wp_ajax_ajax_callback', 'ajax_callback');
    add_action('wp_ajax_nopriv_ajax_callback', 'ajax_callback');

Related posts

Leave a Reply

1 comment

  1. 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.