使用SQL从当前帖子中检索评论

时间:2012-11-20 作者:jaffa

我试图使用下面的代码自动刷新注释,但目前它正在显示所有注释。我只想显示当前帖子的评论。我对SQL不是很有经验,不知道如何执行此操作:

<?php
function dp_recent_comments_ajax() {
        $no_comments = 5;
    $comment_len = 300;
        global $wpdb;

    $request = "SELECT * FROM $wpdb->comments";
    $request .= " JOIN $wpdb->posts ON ID = comment_post_ID";
    $request .= " WHERE comment_approved = \'1\' AND post_status = \'publish\' AND post_password =\'\'";
    $request .= " ORDER BY comment_date DESC LIMIT $no_comments";

    $comments = $wpdb->get_results($request);
    if ($comments) {
        foreach ($comments as $comment) {
            ob_start();
            ?>
                <li>
                    <a style="font-size:12px "href="<?php echo get_permalink( $comment->comment_post_ID ) . \'#comment-\' . $comment->comment_ID; ?>"><?php echo dp_get_author($comment); ?> on <?php echo $comment->comment_date; ?> :</a><br />
                    <span class="recent-comment-text" style="font-size:11px;font-style:italic"><?php echo strip_tags(substr(apply_filters(\'get_comment_text\', $comment->comment_content), 0, $comment_len)); ?>..</span>
                </li>
            <?php
            ob_end_flush();
        }
    } else {
        echo \'<li>\'.__(\'No comments\', \'my-first-wp-theme\').\'</li>\';
    }
    die(); // this is needed for ajax to work properly
}
function dp_get_author($comment) {
    $author = "";

    if ( empty($comment->comment_author) )
        $author = __(\'Anonymous\', \'my-first-wp-theme\');
    else
        $author = $comment->comment_author;

    return $author;
}
add_action(\'wp_ajax_my_recent_comments\', \'dp_recent_comments_ajax\');
add_action(\'wp_ajax_nopriv_my_recent_comments\', \'dp_recent_comments_ajax\'); //for users that are not logged in

1 个回复
SO网友:Mubbashar

在函数中发送您的帖子id,它将如下所示

<?php
 function dp_recent_comments_ajax($ID) {
    $no_comments = 5;
    $comment_len = 300;
    global $wpdb;

$request = "SELECT * FROM $wpdb->comments";
$request .= " JOIN $wpdb->posts ON ID = comment_post_ID";
$request .= " WHERE comment_approved = \'1\' AND post_status = \'publish\' AND post_password =\'\'";
$request .= " AND ID=\'{$ID}\' ";
$request .= " ORDER BY comment_date DESC LIMIT $no_comments";

结束

相关推荐

是什么原因导致wp-Comments-post.php重定向到浏览器的IP地址?

我有一个WordPress副本正在运行,它最近已经从共享主机转移到我控制的VPS上。虽然同一站点的测试副本在同一实例的另一个vhost上、在同一IP地址上正确运行,但在我将公共站点移到另一个vhost上之后,注释表单开始将访问者重定向回自己的IP地址,并显示302 Found 代替成功的302 Moved Temporarily.运行WP 3.4.1,我尝试了:从仪表板重新安装WP,并检查所有插件都是最新的,停用所有插件并将主题设置为211,与工作测试安装不同,以检查它们是否是来自多个IP、计算机和浏览器