Skip to content

Joseph: The Easy Way To Get Recent Comments In WordPress

April 6, 2010

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!🙂

Related posts:

  1. Database Powered CSS in WordPress Themes
  2. WordPress 2.7 Released – XML-RPC and AtomPub Changes
  3. Adding XML-RPC Methods to WordPress

Comments are closed.

%d bloggers like this: