The Easy Way To Get Recent Comments In WordPress

I see lots of tutorials about how to get the most recent comments in WordPress. Many of these involve custom database queries and sometimes a few other additional contortions. There’s no need for any of that, WordPress provides a simple function that does all of the work for you – get_comments. It provides you with an array of comment objects, allowing you to massage the comment data into what ever format you want.

For those that don’t mind reading through the WordPress source code you can find the get_comments function in wp-includes/comment.php. This function first showed up in the 2.7 release, back at the end of 2008.

Here’s a simple example that will return the 5 most recently approved comments:

$recent_comments = get_comments( array(
    'number'    => 5,
    'status'    => 'approve'
) );

That’s all there is to it. You can use get_comments to fetch comments based on a number options: author_email, ID, karma, number, offset, orderby, order, parent, post_id, status, type, and user_id. The power and flexibility of this function really shines through when you combine these options to get just the specific comments you are looking for.

Simplicity isn’t the only reason you should use get_comments instead of a home grown direct database query, it uses the core WordPress object cache hooks. If you are using an object cache plugin (memcached for instance) then this will reduce the number of queries that are sent to your database. Power, flexibility, and performance; what more could you ask for! :-)

No related posts.

This entry was posted in Posts and tagged , . Bookmark the permalink.

10 Responses to The Easy Way To Get Recent Comments In WordPress

  1. Pingback: The Easy Way To Get Recent Comments In WordPress | WPLover

  2. zeo says:

    Was thinking the same thing while back when it was first introduced. Now that you mention it, it reminds me back of this: http://core.trac.wordpress.org/ticket/12904

  3. Dominik Guzei says:

    There is a far better solution to display the most recent comments of your blog: Wizzart – Customizable Recent Comments

    With this plugin you can customize the output of your comments for each widget directly in your backend configuration. Give it a try it will change the way you display recent comments ;-D

    kind regards

  4. Pingback: WordPressハッカーズ

  5. Ramsey says:

    Sorry for a complete n00b question, but how would I modify this to make the most recent comment for a given post show up on the home page loop? Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>