2012-04-26 86 views
3

我正在加载一个帖子与AJAX。 代码是wordpress显示评论从一个帖子检索与AJAX

$(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; 
    }); 
}); 

通过使用此代码自定义模板生成的响应:

<?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; ?> 

Ajax请求的作品,但意见并不show.All后的数据是存在的。 我如何显示评论?

既不comments_template或wp_list_comments工作。

您可以查看演示或下载模板样本我已经做here

+0

'comment_form()'只会显示提交新评论的输入字段,而不会显示任何以前的评论,因此它的工作方式应该如此。你从[print_r(get_comments(array('post_id'=> $ post-> ID)));'? – thv20 2012-04-26 22:38:44

+0

thv20,问题不在comment_form。问题是评论not.get_comments返回正确的数据。我用它在我的第一种方法,但我有一些问题得到所有的信息(回复链接,类...) – Oterox 2012-04-27 07:33:00

回答

1

我已经找到了问题,我忘了设定的全局变量:

global $withcomments; 

我使用

$withcomments = true; 
comments_template(); 

但没有全球它没有工作。

现在像正常的评论那样工作。

+0

我的意思是,你在那个ajax函数中设置它? – 2016-11-03 09:11:02

2

没有(通常comments.php)仅在评论模板太多调整wp_list_comments()作品。

使用get_comments(),通过后ID作为参数:

$comments = get_comments(array ('post_id' => $post->ID); 
if ($comments) 
{ 
    foreach ($comments as $comment) 
    { 
     print "<li>$comment->comment_author<br>$comment->comment_content</li>"; 
    } 
} 
+0

toscho,我曾尝试过,它的工作,但我有一些问题,创建回复链接,并做一些格式,如类,偶,奇怪等。这是我的第一种方法,也有效。 – Oterox 2012-04-27 07:30:48