WordPress Code Snippets

A fresh mix of code snippets and tutorials

WordPress Get Recent Comments

278

In this tutorial, you’ll learn two ways to get the most recent comments on your WordPress-powered site. The first method uses get_comments(),and the second method uses the newer WP_Comment_Query class.

Working on my free WordPress theme template, I wanted to include a function for getting the most recent comments. It’s a great way to highlight active conversations on your site. Either of these techniques could be used to display recent comments in the sidebar, post footer, or anywhere else in the theme template.

Get recent comments: Method 1

This technique uses get_comments() to get an array of recent comments:

Once the comments array is stored in the $recent_comments variable, we loop through each of the comments and display their associated data as desired. This code should be placed directly in the theme template of your choice, like sidebar.php or similar. For the shapeSpace_truncate_string() function, keep reading.. we’ll get to that at the end of the tutorial.

Get recent comments: Method 2

This technique uses the newer WP_Comment_Query class to get an array of recent comments:

This function can be modified as desired and added to your theme’s functions.php file. Then to display the comments anywhere in your theme template, you can do something like this:

Again, you’ll want to customize the markup and attributes as needed to suit your needs. This is the preferred method of getting/displaying recent posts, as it uses the much more robust and flexible WP_Comment_Query class. Everything else in the example function and template code should be self-explanatory, except perhaps the shapeSpace_truncate_string() function, which we’ll look at next..

Truncating the comment text

Each of the previous snippets truncates the comment text using the following function:

This function is from my WP starter theme template, which is available as a free download. The truncate-string function is nice because it doesn’t indiscriminately chop off text when the limit is reached; rather, it only truncates text at the word level, and then includes “...” to make it all crystal clear to the user.

Learn more

WordPress Themes In Depth


Show Support

Like our new Facebook Page to show support!