2012-04-26 88 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