Enquire

WordPress – Get Recent Comments & Blog Post Details

Wordpress Tips & Code Snippets

Retrieving recent comments in WordPress is pretty standard/easy, you can do it by using the get_comments function.

The syntax requires a foreach loop, and is used as follows:

Get recent wordpress comments

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$args = array(
 'number' => '7',
 'status' => 'approve',
);
 
$comments = get_comments($args);
foreach($comments as $comment)
{
echo $comment->comment_content;
echo "<br />";
echo $comment->comment_author;
}

The code above will retrieve 7 of the most recently approved comments. However, getessay.org
if you also want to retrieve details of the blog post that the comments are associated with, it requires a little more work as they’re not returned in the get_comments function…

Get recent comments & blog post details

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 
//get recent comment arguments
$args = array(
 'number' => '7',
 'status' => 'approve',
);
 
//get recent comments
$comments = get_comments($args);
 
//initialize array
$postids = array();
 
//run the comments through a loop to get the post id of each comment and put them into an array
foreach($comments as $comment)
{
 array_push($postids, $comment->comment_post_ID);
}
 
//use the get_posts functions to ONLY get the post details for the recent comments
$comment_post_details = get_posts(array('include' => $postids));
 
//initialize array
$post_details = array();
 
//put the post details into an array
foreach($comment_post_details as $comment_post_details)
{
 $post_details[$comment_post_details->ID] = $comment_post_details;
}
 
//loop the comments array again to print the comments and post details together
foreach($comments as $comment)
{
 //print blog post title
 echo $post_details[$comment->comment_post_ID]->post_title;
 
 //print blog post content
 echo $comment->comment_content;
 
 //print comment author
 echo $comment->comment_author;
}

In theory, we could run the get_post function inside the comments loop, which means only one foreach loop would be required, and consequently the code would be a lot shorter, simpler and cleaner. However, looping the get_post function inside the comment foreach would equate to a lot more MySQL queries being run. So for example, to get the 7 recent comments, an additional 7 queries would have been run to get the post details for each comment, on top of the 1 query to get the comments. In the example I’ve used, only 2 queries are used in total- one to retrieve the comments, the other to retrieve all the post details.

If anyone can improve the code or has a better way to achieve the required result, please leave a comment below!

Comments

Leave a reply

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

X