如何在WordPress的评论区顶部显示当前登录用户的评论?

时间:2016-03-10 作者:Chris Johnson

我想做的是在Wordpress的评论部分的列表顶部显示当前登录用户对任何给定帖子的评论。我不在乎它是否只是复制在顶部,并且仍然按照下面的常规顺序显示,我只需要它显示在列表的顶部,以便用户可以轻松找到它。我找到了如何挑出他们的评论,这样我就可以用CSS来设置它的样式,但改变它在列表中的显示位置却让我不知所措。任何帮助都将不胜感激,提前感谢各位。

add_filter( \'comment_class\', \'comment_class_logged_in_user\' );

function comment_class_logged_in_user( $classes ) {
    global $comment;
    if ( $comment->user_id > 0 && is_user_logged_in() ) {
        global $current_user; get_currentuserinfo();
        $logged_in_user = $current_user->ID;
        if( $comment->user_id == $logged_in_user ) $classes[] = \'comment-author-logged-in\';
    }
return $classes;
}
这是我为wp\\u comment\\u查询所做的尝试,但它不起作用。

<?php
global $current_user; get_currentuserinfo();
$logged_in_user = $current_user->ID;
$args = array(
   \'user_id\' => \'$logged_in_user\',
);

// The Query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );

// Comment Loop
if ( $comments ) {
    foreach ( $comments as $comment ) {
        echo \'<p>\' . $comment->comment_content . \'</p>\';
    }
} else {
    echo \'No comments found.\';
}
?>

2 个回复
SO网友:Chris Johnson

好吧,我知道了。谢谢大家的指点!

<?php
global $current_user,$post;
$args = array(\'user_id\' => $current_user->ID,\'post_id\' => $post->ID);

// The Query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );

// Comment Loop
if ( $comments ) {
    foreach ( $comments as $comment ) {
        echo \'<p>\' . $comment->comment_content . \'</p>\';
    }
} else {
    echo \'No comments found.\';
}
?>

SO网友:darrinb

以下是一种快速而肮脏的方式来为登录用户获取评论:

<?php
$author_id = get_current_user_id();
if( $author_id > 0 ) {
    global $post;
    $args = array(
        \'user_id\' => $author_id,
        \'post_id\' => absint( $post->ID),
        \'number\' => 5,
    );

    $sticky_comments = get_comments( $args );

    if( $sticky_comments ) :
        foreach ( $sticky_comments as $comment ) {
            echo \'<p>\' . $comment->comment_content . \'</p>\';
        }
    else :
        echo \'No comments found. \';
    endif;
}
?>
这将使用登录用户的作者id运行注释查询。确保仅在从返回ID时运行查询get_current_user_id();.

然后,您可以在注释模板中的这个循环之后运行正常的注释循环。