wordpress页面显示当前用户帖子的最新评论

时间:2017-12-19 00:07:00

标签: php wordpress custom-wordpress-pages

在我的wordpress网站上,我让注册用户在网站上发帖,现在我需要制作一个页面,显示当前用户帖子的最新评论。

我找到了这段代码ref,它显示了当前用户的评论,而不是他帖子上的评论

<?php
/*
Plugin Name: Show Recent Comments by a particular user
Plugin URI: http://blog.ashfame.com/?p=876
Description: Provides a shortcode which you can use to show recent comments by a particular user
Author: Ashfame
Author URI: http://blog.ashfame.com/
License: GPL
Usage: 
*/

add_shortcode ( 'show_recent_comments', 'show_recent_comments_handler' );

function show_recent_comments_handler( $atts, $content = null )
{
    extract( shortcode_atts( array( 
        "count" => 10,
        "pretty_permalink" => 0
        ), $atts ));

    $output = ''; // this holds the output
    
    if ( is_user_logged_in() )
    {
        global $current_user;
        get_currentuserinfo();

        $args = array(
            'user_id' => $current_user->ID,
            'number' => $count, // how many comments to retrieve
            'status' => 'approve'
            );

        $comments = get_comments( $args );
        if ( $comments )
        {
            $output.= "<ul>\n";
            foreach ( $comments as $c )
            {
            $output.= '<li>';
            if ( $pretty_permalink ) // uses a lot more queries (not recommended)
                $output.= '<a href="'.get_comment_link( $c->comment_ID ).'">';
            else
                $output.= '<a href="'.get_settings('siteurl').'/?p='.$c->comment_post_ID.'#comment-'.$c->comment_ID.'">';         
            $output.= $c->comment_content;
            $output.= '</a>';
            $output.= "</li>\n";
            }
            $output.= '</ul>';
        }
    }
    else
    {
        $output.= "<h2>You should be logged in to see your comments. Make sense?</h2>";
        $output.= '<h2><a href="'.get_settings('siteurl').'/wp-login.php?redirect_to='.get_permalink().'">Login Now &rarr;</a></h2>';
    }
    return $output;
}
?>

我可以在此代码中更改哪些内容以使其获取当前用户帖子的评论而不是他自己的评论?

1 个答案:

答案 0 :(得分:3)

Wordpress上的get_comments函数有很多可以通过它的参数。要根据帖子的作者而不是评论的user_id搜索评论,您需要“post_author”参数 -

https://codex.wordpress.org/Function_Reference/get_comments

因此,请考虑相应地更改$ args数组,以便查找current_user的ID为post_author的匹配项:

 $args = array(
        'post_author' => $current_user->ID,
        'number' => $count, // how many comments to retrieve
        'status' => 'approve'
        );
相关问题