I have been tryin for the last few hours to research how to get recent comments from wordpress. here is how I managed to get recent posts....
<h4>Recent Posts</h4>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </li> ';
}
wp_reset_query();
?>
</ul>
how do I get the latest comments..
ps. I have tried to change the posts to comments and doesn't work.
Thanks in advance
Steven
You can retrieve recent comments using get_comments()
.
get_comments()
works in a very similar way to the function you're using to retrieve posts.
<?php $recent_comments = get_comments( array(
'number' => 5, // number of comments to retrieve.
'status' => 'approve', // we only want approved comments.
'post_status' => 'publish' // limit to published comments.
) );
if ( $recent_comments ) {
foreach ( (array) $recent_comments as $comment ) {
// sample output - do something useful here
echo '<a href="' . esc_url( get_comment_link( $comment ) ) . '">' . get_the_title( $comment->comment_post_ID ) . '</a>';
}
}
Further reading: https://codex.wordpress.org/Function_Reference/get_comments