I am currently loading a single post using ajax. While the post loading works ok, I cannot get the comments to load. Here is my code:
My javascript to load the post:
<script>
$(".view_post").click(function(e) {
e.preventDefault();
postid = $(this).attr("rel");
$.ajax({
url:"/wp-admin/admin-ajax.php",
type:'POST',
data:'action=posts_open&postid='+postid,
success: function(html){
$("#b_contentwrapper").empty();
$("#b_contentwrapper").append(html);
}
});
});
</script>
The javascript goes through functions.php this way:
function implement_posts()
{
//<?php
get_template_part( 'loop', 'single' );
die();
}
Now here is the code where I actually load my post content:
<?php
$linkid = "p=".$_POST["postid"];
$posti = new WP_Query($linkid);
$posti->the_post();
echo "Time: ";
the_time('F jS, Y');
echo "<br />";
the_category(', ');
echo "<br />";
the_title();
echo "<br />";
the_content();
echo "<br />";
comment_form();
?>
</div>
<?php if (have_comments()) {
echo "Comments ok";
}
else
{
echo "No comments";
}
?>
Now, even for posts having comments I am getting “No comments” displayed. Everything else works correctly. Can anyone help me out?
Thank you.
3 s
To quote the Codex on the have_comments
function:
This function relies upon the global $wp_query object to be set – this is usually the case from within The Loop
The problem is that your ajax handler creates its own WP_Query object. Note that you are not calling the_post()
, instead you are calling $posti->the_post()
. Same logic applies to comments as well.
Try the following:
if ($posti->have_comments()) {
echo "Comments ok";
} else {
echo "No comments";
}