I see lots of tutorials about how to get the most recentcomments in WordPress. Many of these involve custom database queriesand sometimes a few other additional contortions. There’s no need forany of that, WordPress provides a simple function that does all of thework 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:
1 |
$recent_comments = get_comments( array ( |
2 |
'number' => 5, |
3 |
'status' => 'approve' |
4 |
) ); |
That’s all there is to it. You can use get_comments
tofetch comments based on a number options: author_email, ID, karma,number, offset, orderby, order, parent, post_id, status, type, anduser_id. The power and flexibility of this function really shinesthrough when you combine these options to get just the specificcomments 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 coreWordPress object cache hooks. If you are using an object cache plugin(memcached for instance) then this will reduce the number of queriesthat are sent to your database. Power, flexibility, and performance;what more could you ask for! :-)