WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

$(".view_post").click(function(e) {
    postid = $(this).attr("rel");
                    success: function(html){

The javascript goes through functions.php this way:

function implement_posts()
    get_template_part( 'loop', 'single' );

Now here is the code where I actually load my post content:

    $linkid = "p=".$_POST["postid"];
    $posti = new WP_Query($linkid);
    echo "Time: ";
    the_time('F jS, Y');
    echo "<br />";
    the_category(', ');
    echo "<br />";
    echo "<br />";
    echo "<br />";
    <?php if (have_comments()) {
    echo "Comments ok";
        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.

share|improve this question
$linkid = "p=".$_POST["postid"]; is not verry sql injection safe. although wordpess checks this you might wanna do it yourself. – RTB Jul 31 '12 at 22:49

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";
share|improve this answer

On my opinion, it would be better to go with a JQuery .load($[this].attr('href') '.div-with-content-and-comment');

Than make sure you have a single.php that has the markup with the class="div-with-content-and-comment" you want to load via ajax.

share|improve this answer

Look at the source of have_comments() - this check retrieves data from global $wp_query object, which is not used in your case.

So the first step would be to replace have_comments() check with $posti->have_comments().

share|improve this answer

protected by kaiser Jun 10 '13 at 1:02

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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