I'm currently working on calling the next page of posts through ajax. I'm making my request with jQuery, building a custom query in my php handler function, looping through it and then sending back the HTML. This is my loop:
$args = $_REQUEST['query'];
$request_query = new WP_Query($args);
if ($request_query->have_posts()) {
while ($request_query->have_posts()) {
$request_query->the_post();
if ($post->post_type == 'foo') {
get_template_part('/parts/thumbnail-templates/foo');
} else if ($post->post_type == 'bar') {
get_template_part('/parts/thumbnail-templates/bar');
} else {
get_template_part('/parts/thumbnail-templates/generic');
}
}
}
Everything works correctly and the loop runs as expected, except that I get an error that states $post
is undefined, so my two if
s fail, as well as some lines inside my templates which call metadata like this $post->the_meta_key
.
I figure the reason this happens is that there's some other wp magic that runs behind the scenes and makes $post
available in template files, but not in ajax. Hence, I added global $post;
just before my if
statements and now it works as expected.
The question
Is it okay to call global $post;
inside the loop in ajax or is there a better way to access the current post object? Also, if there are any general best practice suggestions for changes in my approach, please let me know.