3

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.

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');

1 Answer 1

6

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.

1
  • yes mate, got the point and issue solved. Thnx :) Mar 16, 2014 at 20:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.