Skip to content
  • Quick Ref
  • Contact
  • About
wpcanyon.com

wpcanyon.com

Tag: Comments

Show Top Commentators in WordPress Without a Plugin

Posted on August 20, 2025August 20, 2025 By Admin No Comments on Show Top Commentators in WordPress Without a Plugin

Show Top Commentators in WordPress Without a Plugin

If you want to highlight your most engaged readers by showing the top commentators on your WordPress site, you might think you need a plugin. However, you can achieve this easily with a bit of custom code. This tutorial explains how to show top commentators in WordPress without a plugin, giving you full control and keeping your site lightweight.

Quick Fix: Display Top Commentators with Custom Code

  1. Add a custom function to your theme’s functions.php file or a site-specific plugin to query and display top commentators.
  2. Use a shortcode or call the function directly in your theme templates where you want the list to appear.
  3. Style the output with CSS to match your site’s design.

Why This Happens

WordPress stores all comments in the database, including the author’s name and email. By querying this data, you can count how many comments each user has made and display a ranked list. Plugins automate this, but the underlying process is straightforward and can be done manually with a few lines of code.

Step-by-step: Show Top Commentators Without a Plugin

  1. Backup your site: Before editing theme files, always back up your site or use a child theme.
  2. Open your theme’s functions.php file: Access this via Appearance > Theme Editor or FTP.
  3. Add the following function to fetch and display top commentators:
function get_top_commentators( $number = 5 ) {
    global $wpdb;

    // Query to get commenters and their comment counts
    $results = $wpdb->get_results( "
        SELECT comment_author, comment_author_email, COUNT(comment_author_email) AS comment_count
        FROM $wpdb->comments
        WHERE comment_approved = 1
          AND comment_author_email != ''
        GROUP BY comment_author_email
        ORDER BY comment_count DESC
        LIMIT %d
    ", ARRAY_A, $number );

    if ( empty( $results ) ) {
        return '<p>No commentators found.</p>';
    }

    $output = '<ul class="top-commentators">';
    foreach ( $results as $commentator ) {
        $avatar = get_avatar( $commentator['comment_author_email'], 48 );
        $name = esc_html( $commentator['comment_author'] );
        $count = intval( $commentator['comment_count'] );

        $output .= "<li>{$avatar} <strong>{$name}</strong> ({$count} comment" . ( $count > 1 ? 's' : '' ) . ")</li>";
    }
    $output .= '</ul>';

    return $output;
}

// Shortcode to display top commentators anywhere
function top_commentators_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'number' => 5,
    ), $atts, 'top_commentators' );

    return get_top_commentators( intval( $atts['number'] ) );
}
add_shortcode( 'top_commentators', 'top_commentators_shortcode' );
  1. Use the shortcode [top_commentators number="5"] in posts, pages, or widgets to display the top 5 commentators.
  2. Or call echo get_top_commentators(5); directly in your theme files where you want the list.

Discussion Settings & Styling

Make sure your WordPress Discussion Settings allow comments and that comments are approved to be counted.

To style the list, add CSS to your theme’s stylesheet or Customizer:

.top-commentators {
    list-style: none;
    padding: 0;
    margin: 0;
}

.top-commentators li {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.top-commentators img.avatar {
    border-radius: 50%;
    margin-right: 10px;
}

This CSS makes the avatars circular and aligns the list items neatly.

Common Pitfalls

  • No comments showing: Ensure comments are approved and not spam.
  • Empty author emails: Comments without an email are ignored to avoid counting anonymous users multiple times.
  • Function placement: Adding code to a parent theme’s functions.php may be lost on updates. Use a child theme or site-specific plugin.
  • Performance: On very large sites, the query might be slow. Consider caching the output.

Test & Verify

  1. Place the shortcode [top_commentators] on a test page.
  2. Visit the page and verify the list shows commenters with avatars and comment counts.
  3. Test with different number values, e.g. [top_commentators number="10"].
  4. Check on mobile and desktop to confirm styling.
  5. Approve new comments and refresh to see the list update.

Wrap-up

Showing top commentators in WordPress without a plugin is simple and efficient. By adding a custom function and shortcode, you can engage your community and showcase your most active readers without bloating your site. Customize the code and styling to fit your theme and enjoy a more interactive site.

Works on

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Hosting Panels cPanel, Plesk, DirectAdmin
WordPress Versions 4.9 and above (tested on latest versions)

FAQ

Q: Can I limit the list to commenters on a specific post or category?
A: The provided code counts all approved comments site-wide. To limit by post or category, the query needs customization using comment_post_ID or joining with post taxonomy tables.
Q: How do I update the list automatically?
A: The list updates dynamically each time the page loads. For better performance on busy sites, consider caching the output with transients.
Q: Can I show commenters’ website links?
A:
…
Comments

How to Style Admin Comments in WordPress

Posted on August 20, 2025August 20, 2025 By Admin No Comments on How to Style Admin Comments in WordPress

How to Style Admin Comments in WordPress

If you want to visually distinguish comments made by site administrators in your WordPress blog, you need to style admin comments differently. This improves clarity for readers and moderators by highlighting official responses. The quick fix is to add custom CSS targeting admin comment classes WordPress automatically assigns.

Quick Fix

  1. Identify the CSS class WordPress uses for admin comments (usually .bypostauthor).
  2. Add custom CSS to your theme’s style.css or via the Customizer’s Additional CSS panel.
  3. Clear any caching and refresh your comments page to see the changes.

Why This Happens

WordPress automatically adds the bypostauthor class to comments made by the post author, which includes admins if they authored the post. However, if you want to style all admin comments regardless of post authorship, you need to target users with the administrator role specifically. By default, WordPress does not differentiate admin comments beyond post author comments, so custom code or CSS targeting is required.

Step-by-Step

  1. Locate the admin comment class: WordPress adds bypostauthor to comments by the post author.
  2. Target admin users specifically: To style all admin comments, add a filter to add a custom CSS class to admin comments.
  3. Add CSS rules: Use CSS to style the comments with the custom class.
  4. Apply changes: Add code snippets to your theme’s functions.php and CSS to style.css or Customizer.

Discussion Settings & Styling

WordPress discussion settings control comment behavior but do not affect comment styling. Styling is handled purely by CSS and optionally by adding classes via PHP. The key is to ensure admin comments have a distinct CSS class.

  • Default class: bypostauthor for post author comments.
  • Custom class: Add admin-comment for all admin role comments.

Code Snippets

1. Add a custom CSS class to admin comments:

function add_admin_comment_class( $classes, $comment ) {
    $user = get_userdata( $comment->user_id );
    if ( $user && in_array( 'administrator', (array) $user->roles ) ) {
        $classes[] = 'admin-comment';
    }
    return $classes;
}
add_filter( 'comment_class', 'add_admin_comment_class', 10, 2 );

2. Add CSS to style admin comments:

/* Style admin comments with a distinct background and border */
.admin-comment {
    background-color: #f0f8ff;
    border-left: 4px solid #0073aa;
    padding: 10px;
    margin-bottom: 15px;
}
.admin-comment .comment-author {
    font-weight: bold;
    color: #0073aa;
}

Common Pitfalls

  • Not targeting the correct user role: The default bypostauthor class only applies to post authors, not all admins.
  • CSS specificity issues: Your styles may be overridden by theme CSS. Use proper selectors or !important sparingly.
  • Child theme or caching: Changes to functions.php or CSS may not show immediately due to caching or editing the wrong theme.
  • Editing core files: Never edit WordPress core files; use child themes or custom plugins for code snippets.

Test & Verify

  1. Log in as an admin user and leave a comment on a post.
  2. View the post on the front end and inspect the comment’s HTML to confirm the admin-comment class is present.
  3. Verify the custom styles are applied (background color, border, font color).
  4. Test with comments from non-admin users to ensure they are not styled.
  5. Clear any caching plugins or browser cache if changes don’t appear.

Wrap-up

Styling admin comments in WordPress requires adding a custom CSS class to comments made by administrators and then applying CSS styles to that class. By default, WordPress only marks post author comments, so adding a filter to target all admin users is necessary. This approach improves comment clarity and user experience without modifying core files.

Works on: Apache, Nginx, LiteSpeed servers; compatible with cPanel, Plesk hosting environments; works with most themes and child themes; requires PHP access to add filter and CSS access via theme or Customizer.

FAQ

Q: Can I style comments from other user roles differently?
A: Yes, by modifying the add_admin_comment_class function to check for other roles and add different CSS classes.
Q: What if my theme already styles bypostauthor comments?
A: You can override those styles by adding your own CSS with higher specificity or use the new admin-comment class for more control.
Q: Can I add this functionality without editing functions.php?
A: Yes, by using a site-specific plugin or a code snippets plugin to add PHP code safely.
Q: Will this work with comment plugins like Disqus?
A: No, third-party comment systems often replace the default WordPress comment markup, so custom styling requires their specific methods.
Q: How do I remove the styling if I change my mind?
A: Remove the PHP filter code and the CSS rules you added. Clear caches to ensure changes take effect.
…
Admin & UI

Displaying What Time Ago a Post or Comment Is Published in WordPress

Posted on August 20, 2025August 20, 2025 By Admin No Comments on Displaying What Time Ago a Post or Comment Is Published in WordPress

Displaying What Time Ago a Post or Comment Is Published in WordPress

Showing how long ago a post or comment was published is a popular feature that improves user engagement and readability on WordPress sites. Instead of displaying a static date and time, you can show dynamic, human-friendly timestamps like “5 minutes ago” or “2 days ago.” This guide explains how to quickly implement this feature for both posts and comments using WordPress functions and custom code snippets.

Quick Fix

  1. Use WordPress’s built-in human_time_diff() function to calculate the time difference between the current time and the post or comment date.
  2. Modify your theme’s template files (e.g., single.php for posts, comments.php for comments) to replace the static date with a dynamic “time ago” string.
  3. Optionally, add CSS styling to ensure the new timestamps fit your site’s design.

Why This Happens

By default, WordPress displays the published date and time in a fixed format (e.g., “March 15, 2024 at 3:00 pm”). While precise, this format can be less intuitive for users who want to quickly understand how recent a post or comment is. Using relative time (“time ago”) improves readability and user experience by providing context at a glance.

Step-by-step

1. Displaying “Time Ago” for Posts

Edit your theme’s single.php or wherever the post date is displayed. Replace the existing date output with the following code snippet:

<?php
$time_diff = human_time_diff( get_the_time('U'), current_time('timestamp') );
echo sprintf( esc_html__( '%s ago', 'your-text-domain' ), $time_diff );
?>

This code calculates the difference between the post’s publish time and the current time, then outputs it in a localized “X ago” format.

2. Displaying “Time Ago” for Comments

Edit your theme’s comments.php file or wherever comment dates are shown. Replace the comment date output with:

<?php
$comment_time = get_comment_time('U');
$time_diff = human_time_diff( $comment_time, current_time('timestamp') );
echo sprintf( esc_html__( '%s ago', 'your-text-domain' ), $time_diff );
?>

3. Optional: Adding a Title Attribute for Exact Date

For accessibility and clarity, you can add a tooltip showing the exact date on hover:

<?php
$exact_date = get_the_date();
$time_diff = human_time_diff( get_the_time('U'), current_time('timestamp') );
?>
<time title="<?php echo esc_attr( $exact_date ); ?>">
  <?php echo sprintf( esc_html__( '%s ago', 'your-text-domain' ), $time_diff ); ?>
</time>

Discussion Settings & Styling

WordPress’s Discussion settings do not affect how dates are displayed but control comment moderation and display options. To style the “time ago” text, add CSS targeting the <time> tag or a custom class you add around the timestamp.

Example CSS:

time.time-ago {
  color: #666;
  font-style: italic;
  font-size: 0.9em;
}

Wrap your PHP output in a <time class="time-ago"> tag for styling:

<time class="time-ago" title="<?php echo esc_attr( $exact_date ); ?>">
  <?php echo sprintf( esc_html__( '%s ago', 'your-text-domain' ), $time_diff ); ?>
</time>

Code Snippets

Here are reusable functions you can add to your theme’s functions.php or a custom plugin for cleaner templates.

/**
 * Returns a formatted "time ago" string for a post.
 *
 * @param int|null $post_id Post ID. Defaults to current post.
 * @return string Human-readable time ago string.
 */
function get_post_time_ago( $post_id = null ) {
    $post_id = $post_id ? $post_id : get_the_ID();
    $time_diff = human_time_diff( get_post_time('U', false, $post_id), current_time('timestamp') );
    return sprintf( esc_html__( '%s ago', 'your-text-domain' ), $time_diff );
}

/**
 * Returns a formatted "time ago" string for a comment.
 *
 * @param int|null $comment_id Comment ID. Defaults to current comment in loop.
 * @return string Human-readable time ago string.
 */
function get_comment_time_ago( $comment_id = null ) {
    $comment = $comment_id ? get_comment( $comment_id ) : get_comment();
    $time_diff = human_time_diff( strtotime( $comment->comment_date_gmt ), current_time('timestamp') );
    return sprintf( esc_html__( '%s ago', 'your-text-domain' ), $time_diff );
}

Usage in templates:

<?php echo get_post_time_ago(); ?>

<?php echo get_comment_time_ago(); ?>

Common Pitfalls

  • Timezones: Always use current_time('timestamp') instead of time() to respect WordPress timezone settings.
  • Translation: Wrap strings in esc_html__() or similar functions for localization.
  • Theme Overrides: Some themes hardcode dates in JavaScript or use custom functions—check your theme’s documentation before editing.
  • Caching: If you use caching plugins, dynamic “time ago” values may not update frequently. Consider using JavaScript for live updates if needed.

Test & Verify

  1. Clear your site cache and browser cache.
  2. Visit a single post page and verify the post date shows as “X ago.”
  3. View comments and confirm comment dates also display “X ago.”
  4. Hover over the timestamp to see the exact date if you added the title attribute.
  5. Test on different devices and browsers to ensure consistent display.

Wrap-up

Displaying “time ago” for posts and comments in WordPress is…

Comments

Disable comments sitewide (and close on old posts)

Posted on August 19, 2025 By Admin No Comments on Disable comments sitewide (and close on old posts)

Disable Comments Sitewide (and Close on Old Posts) in WordPress

Comments can sometimes attract spam, require moderation, or simply no longer fit the purpose of your WordPress site. Disabling comments sitewide and closing comments on older posts is a straightforward way to maintain control over user interaction and reduce maintenance. This guide shows you how to quickly disable comments across your entire WordPress site and automatically close comments on posts older than a specified number of days.

Quick Fix: Disable Comments Sitewide

  1. Go to your WordPress admin dashboard.
  2. Navigate to Settings > Discussion.
  3. Uncheck Allow people to submit comments on new posts.
  4. Save changes.
  5. To disable comments on existing posts, use the bulk edit feature or apply a code snippet (see below).
  6. To close comments on old posts automatically, add a custom function to your theme’s functions.php file or a site-specific plugin.

Why This Happens

By default, WordPress allows comments on new posts unless disabled manually. Existing posts retain their comment status unless changed individually or programmatically. Older posts may continue to accept comments indefinitely, which can lead to spam or outdated discussions. Disabling comments sitewide and closing them on older posts helps maintain site cleanliness and reduces moderation workload.

Step-by-Step: Disable Comments Sitewide and Close on Old Posts

1. Disable Comments on New Posts via Settings

This prevents comments on all future posts.

Dashboard > Settings > Discussion
- Uncheck "Allow people to submit comments on new posts"
- Save Changes

2. Disable Comments on Existing Posts in Bulk

Use WordPress bulk edit to disable comments on existing posts:

  1. Go to Posts > All Posts.
  2. Select all posts (increase posts per page if needed).
  3. Choose Edit from the Bulk Actions dropdown and click Apply.
  4. Set Comments to Do not allow.
  5. Click Update.

3. Programmatically Close Comments on Old Posts

Add the following code snippet to your theme’s functions.php file or a site-specific plugin. This will automatically close comments on posts older than 30 days (adjustable):

function close_comments_on_old_posts( $open, $post_id ) {
    $days = 30; // Number of days after which comments close
    $post = get_post( $post_id );
    if ( 'post' === $post-post_type ) {
        $post_age = ( time() - strtotime( $post-post_date ) ) / DAY_IN_SECONDS;
        if ( $post_age $days ) {
            return false; // Close comments
        }
    }
    return $open;
}
add_filter( 'comments_open', 'close_comments_on_old_posts', 10, 2 );

4. Disable Comments on Other Content Types

To disable comments on pages or custom post types, extend the bulk edit or use this snippet to disable comments sitewide:

function disable_comments_everywhere() {
    // Disable support for comments and trackbacks in post types
    foreach ( get_post_types() as $post_type ) {
        if ( post_type_supports( $post_type, 'comments' ) ) {
            remove_post_type_support( $post_type, 'comments' );
            remove_post_type_support( $post_type, 'trackbacks' );
        }
    }
}
add_action( 'admin_init', 'disable_comments_everywhere' );

// Close comments on front-end
function filter_comments_open( $open, $post_id ) {
    return false;
}
add_filter( 'comments_open', 'filter_comments_open', 20, 2 );
add_filter( 'pings_open', 'filter_comments_open', 20, 2 );

Common Pitfalls

  • Theme or plugin overrides: Some themes or plugins may override comment settings. Check for theme options or plugin settings that enable comments independently.
  • Cached pages: If you use caching plugins or server caching, changes may not appear immediately. Clear caches after applying changes.
  • Bulk edit limits: Bulk editing posts is limited by the number of posts shown per page. Increase the number of posts per page or repeat the process for all pages.
  • Child theme usage: When adding code snippets, use a child theme or a site-specific plugin to avoid losing changes after theme updates.

Works on

This method works on all standard WordPress setups regardless of the web server:

  • Apache
  • Nginx
  • LiteSpeed
  • cPanel and Plesk hosting environments
  • Multisite WordPress installations (note: bulk edit applies per site)

FAQ

Q: Will disabling comments delete existing comments?
No, disabling comments only prevents new comments. Existing comments remain visible unless you delete them manually.
Q: Can I disable comments only on pages and not posts?
Yes. You can selectively disable comments by modifying the code snippet to target only the ‘page’ post type or use bulk edit on pages only.
Q: How do I re-enable comments later?
Simply reverse the changes: enable comments in Settings > Discussion, remove or comment out the code snippets, and bulk edit posts/pages to allow comments again.
Q: Does this method affect pingbacks and trackbacks?
The provided code disables both comments and pingbacks/trackbacks. You can adjust the filters if you want to keep pingbacks enabled.
Q: Is there a plugin alternative?
Yes, plugins like “Disable Comments” offer UI-based options to disable comments sitewide or selectively. However, manual code snippets provide more control and avoid plugin bloat.
…
Admin & Blocks

Get Separate Count For Comments, Trackbacks, And Pingbacks In WordPress

Posted on August 19, 2025 By Admin No Comments on Get Separate Count For Comments, Trackbacks, And Pingbacks In WordPress

Get Separate Count For Comments, Trackbacks, And Pingbacks In WordPress

If you want to display or process separate counts for comments, trackbacks, and pingbacks in WordPress, the default comment count won’t suffice. WordPress lumps all these types together, making it hard to distinguish between genuine user comments and automated or external references like trackbacks and pingbacks. This tutorial shows you how to get accurate, separate counts for each type quickly and reliably.

Quick Fix

  1. Use WordPress’s get_comments() function with the type argument to fetch comments, trackbacks, or pingbacks separately.
  2. Create custom functions to return counts for each comment type.
  3. Add these functions to your theme’s functions.php file or a small custom plugin.
  4. Use these functions in your templates or blocks to display separate counts.

Why This Happens

WordPress stores comments, trackbacks, and pingbacks in the same database table (wp_comments) and by default, functions like get_comments_number() or comments_number() return a combined count. Trackbacks and pingbacks are types of comments but serve different purposes:

  • Comments: User-generated feedback or discussion.
  • Trackbacks: Notifications from other blogs linking to your post.
  • Pingbacks: Automated notifications from other WordPress sites linking to your post.

Separating these counts helps you better understand engagement and manage spam or external references more effectively.

When to Use Separate Counts

  • Displaying genuine user interaction separately from automated or external references.
  • Filtering or moderating comments, trackbacks, and pingbacks differently.
  • Creating custom reports or analytics on engagement types.
  • Improving UI/UX by showing distinct counts in post meta or widgets.

Updated Code for Modern WordPress

Modern WordPress (5.0+) supports querying comments by type using the get_comments() function with the type parameter. Below are three functions to get counts for comments, trackbacks, and pingbacks separately.

/**
 * Get count of approved comments for a post.
 *
 * @param int $post_id Post ID.
 * @return int Number of approved comments.
 */
function get_approved_comment_count( $post_id ) {
    $comments = get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='comment',
        'count'   =true,
    ) );
    return $comments;
}

/**
 * Get count of approved trackbacks for a post.
 *
 * @param int $post_id Post ID.
 * @return int Number of approved trackbacks.
 */
function get_approved_trackback_count( $post_id ) {
    $trackbacks = get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='trackback',
        'count'   =true,
    ) );
    return $trackbacks;
}

/**
 * Get count of approved pingbacks for a post.
 *
 * @param int $post_id Post ID.
 * @return int Number of approved pingbacks.
 */
function get_approved_pingback_count( $post_id ) {
    $pingbacks = get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='pingback',
        'count'   =true,
    ) );
    return $pingbacks;
}

How to Add This Code

Option 1: Add to Your Theme’s functions.php

  1. Open your active theme folder.
  2. Locate and open functions.php.
  3. Paste the above functions at the end of the file.
  4. Save the file and upload if editing locally.

Option 2: Create a Small Custom Plugin

  1. Create a new folder named comment-type-counts in wp-content/plugins/.
  2. Create a file comment-type-counts.php inside that folder.
  3. Paste the following code into that file:
<?php
/*
Plugin Name: Comment Type Counts
Description: Provides functions to get separate counts for comments, trackbacks, and pingbacks.
Version: 1.0
Author: Your Name
License: GPL2
*/

function get_approved_comment_count( $post_id ) {
    return get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='comment',
        'count'   =true,
    ) );
}

function get_approved_trackback_count( $post_id ) {
    return get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='trackback',
        'count'   =true,
    ) );
}

function get_approved_pingback_count( $post_id ) {
    return get_comments( array(
        'post_id' =$post_id,
        'status'  ='approve',
        'type'    ='pingback',
        'count'   =true,
    ) );
}
?>
  1. Activate the plugin from the WordPress admin dashboard.

Step-by-Step Test

  1. Ensure your posts have comments, trackbacks, and pingbacks approved.
  2. Open your theme’s single post template file (usually single.php or a template part).
  3. Insert the following code snippet where you want to display the counts:
<?php
$post_id = get_the_ID();

$comment_count = get_approved_comment_count( $post_id );
$trackback_count = get_approved_trackback_count( $post_id );
$pingback_count = get_approved_pingback_count( $post_id );
?>

<div class="comment-type-counts">
    <p>Comments: <?php echo esc_html( $comment_count ); ?></p>
    <p>Trackbacks: <?php echo esc_html( $trackback_count ); ?></p>
    <p>Pingbacks: <?php echo esc_html( $pingback_count ); ?></p>
</div>
…
WordPress Snippets

Showing Amount Of Comments A Comment Author Made

Posted on August 19, 2025 By Admin No Comments on Showing Amount Of Comments A Comment Author Made

Showing Amount Of Comments A Comment Author Made

When managing a WordPress site, you might want to display how many comments a particular comment author has made. This can add social proof, encourage engagement, or simply provide context to readers. The quick fix is to use a custom function that counts comments by author and then display that count alongside their comment.

Quick Fix: Count Comments by Author WordPress

  1. Add a custom function to your functions.php file or a small custom plugin that counts comments by the author’s email or user ID.
  2. Modify your comment template to display the count next to each comment author.
  3. Test to ensure the count updates correctly for each commenter.

Why This Happens

By default, WordPress does not show how many comments a user or guest commenter has made. This is because comments are stored individually without aggregation by author. To display the number of comments an author has made, you need to query the database and count comments associated with that author’s email or user ID.

This is especially useful for community sites, forums, or blogs with active discussions where recognizing frequent commenters adds value.

Step-by-Step: Updated Code for Modern WordPress

The following example uses WordPress core functions and best practices to count comments by author email (works for both logged-in users and guest commenters):

<?php
/**
 * Get the number of approved comments by a comment author.
 *
 * @param WP_Comment $comment Comment object.
 * @return int Number of approved comments by the author.
 */
function get_comment_author_comment_count( $comment ) {
    if ( ! $comment instanceof WP_Comment ) {
        return 0;
    }

    $author_email = $comment->comment_author_email;

    if ( empty( $author_email ) ) {
        return 0;
    }

    $args = array(
        'author_email'   => $author_email,
        'status'         => 'approve',
        'count'          => true,
    );

    $count = get_comments( $args );

    return (int) $count;
}
?>

To display this count next to each comment author in your theme’s comments.php or comment template part, add:

<?php
$comment_count = get_comment_author_comment_count( $comment );
if ( $comment_count > 1 ) {
    echo '<span class="comment-author-count">(' . esc_html( $comment_count ) . ' comments)</span>';
}
?>

How to Add via functions.php or a Small Plugin

  1. Open your active theme’s functions.php file or create a new plugin file (e.g., comment-author-count.php).
  2. Paste the get_comment_author_comment_count() function into the file.
  3. Modify your comment template to call this function and output the count as shown above.
  4. Save and upload the changes.

If you prefer a plugin, wrap the function in plugin headers like this:

<?php
/*
Plugin Name: Comment Author Comment Count
Description: Displays the number of comments a comment author has made.
Version: 1.0
Author: Your Name
License: GPL2
*/

function get_comment_author_comment_count( $comment ) {
    if ( ! $comment instanceof WP_Comment ) {
        return 0;
    }

    $author_email = $comment->comment_author_email;

    if ( empty( $author_email ) ) {
        return 0;
    }

    $args = array(
        'author_email'   => $author_email,
        'status'         => 'approve',
        'count'          => true,
    );

    $count = get_comments( $args );

    return (int) $count;
}
?>

Step-by-Step Test

  1. Ensure your site has multiple comments from the same author (same email address).
  2. Add the function to functions.php or activate your plugin.
  3. Edit your theme’s comment template (usually comments.php) to call get_comment_author_comment_count( $comment ) and display the count.
  4. Visit a post with comments and verify the count appears next to the author’s name.
  5. Try commenting again with the same email and refresh to see the count increase.

Block Themes & Gutenberg Notes

With the rise of block themes and Gutenberg, comments are often rendered via blocks or server-side rendering. To integrate this functionality:

  • If your theme uses the core/comment block, you may need to create a custom block variation or extend the comment rendering via render_callback in PHP.
  • Use the same get_comment_author_comment_count() function inside your block’s PHP render callback to output the count.
  • For block-based themes, consider creating a small plugin that hooks into comment rendering filters like comment_text or comment_author to append the comment count dynamically.

Common Pitfalls

  • Counting by email only: Guest commenters with different emails will be counted separately even if they are the same person.
  • Performance: Counting comments for every comment on a large site can cause performance issues. Consider caching results if needed.
  • Comment moderation: Only approved comments are counted to avoid showing counts for spam or pending comments.
  • Theme compatibility: Some themes heavily customize comment output; ensure you insert the code in the correct template file.

Works on

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Control Panels cPanel, Plesk, DirectAdmin
WordPress Versions 5.0 and above (modern block and classic themes)
Themes Classic PHP templates, Block themes with minor adjustments

FAQ

…
WordPress Snippets

Recent Posts

  • Top WordPress Themes for Blogs in 2025
  • WordPress Admin Panel Trick: Adding ID Field to the Posts Listing
  • Solution previous_posts_link and next_posts_link Not Working
  • Show Top Commentators in WordPress Without a Plugin
  • How to Style Admin Comments in WordPress

Recent Comments

    Archives

    • August 2025

    Categories

    • Admin & Blocks
    • Admin & UI
    • Automation
    • Automation & Plugins
    • Comments
    • Comparisons
    • Database & Revisions
    • Developer Snippets
    • Fixes & Errors
    • Media & Thumbnails
    • Queries & Pagination
    • Security
    • Speed & Security
    • Tips & Tricks
    • WooCommerce How‑tos
    • WordPress Snippets
    • WordPress Themes
    • Terms & Conditions
    • Affiliate Disclosure

    Copyright © 2025 wpcanyon.com.

    Powered by PressBook WordPress theme

    Also by the maker of MySurveyReviews.com