Blog / WordPress/ How to Display a List of Posts with Recent Comments in WordPress

How to Display a List of Posts with Recent Comments in WordPress

WordPress调用最新评论的文章列表

Introduction

Displaying a list of posts with the most recent comments is a feature similar to showcasing a site's "most discussed posts." Unlike directly listing comments, its core purpose is to retrieve posts that have recent comments and sort them in descending order based on the timestamp of their latest comment. This helps visitors quickly discover popular, recently discussed content, enhancing the visibility of interactive elements on your site. The final output is typically a list of post titles with links.

Implementation Code

The following PHP code snippet demonstrates how to implement this feature within a WordPress theme file. Place the code where you want the list to appear (e.g., sidebar, post footer).

<?php
global $wpdb;
// Query IDs of published posts with recent approved comments
$pop = $wpdb->get_results(
    "SELECT DISTINCT comment_post_ID
    FROM $wpdb->comments
    WHERE comment_approved = '1' // Only approved comments
    AND comment_post_ID NOT IN (
        SELECT ID FROM $wpdb->posts
        WHERE post_type != 'post' // Exclude non-'post' types
        OR post_status != 'publish' // Exclude unpublished posts
        OR post_password != '' // Exclude password-protected posts
    )
    ORDER BY comment_date_gmt DESC // Sort by latest comment
    LIMIT 10" // Limit to 10 posts
);
?>
<?php if ($pop) : ?>
    <ul>
        <?php foreach ($pop as $post_item) : ?>
            <?php $post_id = $post_item->comment_post_ID; ?>
            <li>
                <a href="<?php echo get_permalink($post_id); ?>">
                    <?php echo get_the_title($post_id); ?>
                </a>
            </li>
        <?php endforeach; ?>
    </ul>
<?php else : ?>
    <p>No posts with comments yet.</p>
<?php endif; ?>

Explanation & Notes

  • Core Logic: The code queries the database directly for post IDs with recently approved comments, then loops through to output titles and links.
  • Query Optimization: DISTINCT ensures each post appears only once. The subquery excludes non-public posts, non-'post' types, and password-protected posts for accuracy and security.
  • Variable Safety: The variable name $post_item is used to avoid conflict with WordPress's global $post variable.
  • Error Handling: The if ($pop) check prevents outputting an empty list or errors when no posts have comments.
  • Customization: Change the number after LIMIT to control how many posts are shown. Style the <ul> list with CSS.

Post a Comment

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