Show Recent Comments

The following code will create a wordpress shortcode that you may use anywhere on your site.

function recent_comments()
{
    $recentcomments = get_comments(array( 
        'number'      => 10, // number of comments
        'status'      => 'approve',
        'post_status' => 'publish',
        'author__not_in' => 1 // exclude admin
    ));

    if ($recentcomments) {
        $output .= 'Recent 10 comments<br />';
        $output .= '<ul>';

        foreach ((array)$recentcomments as $comment) {
            $comment_author_link = get_comment_author_link($comment); // commentator name and link
            $comment_post_link = esc_url(get_comment_link($comment)); // link of post commentator comment on
            $comment_post_title = get_the_title($comment->comment_post_ID); // title of post commentator comment on
            $comment_excerpt = wp_trim_words(get_comment_excerpt($comment), 9); // the comments, trimmed to first 9 words

            $output .= '<li class="recent_comments">' . $comment_author_link . ' on <a href="' . comment_post_link . '">' . $comment_post_title . '</a> &rarr; ' .   $comment_excerpt .'</li>';
            // sample output:
            // Guest on Post Title
            // Hello there, this is my comment to your blog…
        }

        $output .= '</ul>';	
    }

    return $output;
}
add_shortcode('recent_comments', recent_comments);

You may see it in action on this page.

Categories: Tutorials

Please Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.