wordpress showing comments from a post retrieved w

2019-07-06 09:20发布

i'm loading a post with ajax. The code is

$(document).ready(function(){

    loadPostsFun = function(){
        $.ajax({
            url: "http://lab1.koalamedia.es/ajax/",
            //url: "/random/",
            success: function(response){
                $("#randomPost").html( response );
            }
        });
    };
    $("#another").click(function(){
        loadPostsFun();
        return false;
    });
});

The response is generated by a custom template with this code:

<?php
    query_posts('showposts=1&orderby=rand');
    the_post();
    $args = array( 'numberposts' => 1, 'orderby' => 'date' );
    $rand_posts = get_posts( $args );
?>
<?php
    foreach( $rand_posts as $post ) :  setup_postdata($post);
?>

    <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
      <?php if ( is_front_page() ) { ?>
        <h2 class="entry-title"><?php the_title(); ?></h2>
        <?php } else { ?>
          <h1 class="entry-title"><?php the_title(); ?></h1>
        <?php } ?>

         <div class="entry-content">
          <?php the_content(); ?>
          <?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
        <?php comments_popup_link(__('Comments (0)'), __('Comments (1)'), __('Comments (%)')); ?>
        </div><!-- .entry-content -->
      </div><!-- #post-## -->

      <?php 

        //comments_template( '', true ); //this doesn't work
        comment_form(); 
        //wp_list_comments(''); //this doesn't work

      ?>
<?php endforeach; ?>

The ajax request works but the comments doesn't show.All the post data is there. How can i show the comments?

neither comments_template or wp_list_comments work.

You can view a demo or download the template sample i've done here

2条回答
放我归山
2楼-- · 2019-07-06 09:26

Without much tweaking wp_list_comments() works in a comments template (usually comments.php) only.

Use get_comments(), pass the post ID as parameter:

$comments = get_comments(array ( 'post_id' =>  $post->ID );
if ( $comments )
{
    foreach ( $comments as $comment )
    {
        print "<li>$comment->comment_author<br>$comment->comment_content</li>";
    }
}
查看更多
我只想做你的唯一
3楼-- · 2019-07-06 09:36

i've found the problem, i forgot to set the global variable:

global $withcomments;

i was using

$withcomments = true; 
comments_template();

but without the global it didn't work.

Now works like normal comments do.

查看更多
登录 后发表回答