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');
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 onis_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:Your ajax request would then include
ajax_object.is_single
as part of the query parameters as in this example from the Codex, which passedajax_object.we_value
through aswhatever
Your callback would then have access to the data via
$_POST
.