Halloween Sale 15% off Ends in See the plans
PHP

Top Commenters Shortcode

Adds a [wpide_top_commenters] shortcode listing the people who left the most approved comments, a simple way to thank your community.

Don’t have WPIDE yet? Install it on your site

Code

add_shortcode( 'wpide_top_commenters', function ( $atts ) {
    global $wpdb;

    $atts   = shortcode_atts( array( 'number' => 10, 'days' => 365 ), $atts, 'wpide_top_commenters' );
    $number = min( 50, absint( $atts['number'] ) );
    $days   = absint( $atts['days'] );
    $key    = 'wpide_top_commenters_' . $number . '_' . $days;
    $rows   = get_transient( $key );

    if ( false === $rows ) {
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT comment_author AS name, COUNT(*) AS total
             FROM {$wpdb->comments}
             WHERE comment_approved = '1' AND comment_type IN ('comment', '') AND comment_author_email <> ''
               AND comment_date_gmt > %s
             GROUP BY comment_author_email, comment_author
             ORDER BY total DESC
             LIMIT %d",
            gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ),
            $number
        ) );
        set_transient( $key, $rows, 12 * HOUR_IN_SECONDS );
    }

    if ( ! $rows ) {
        return '';
    }

    $html = '<ol class="wpide-top-commenters">';
    foreach ( $rows as $row ) {
        $html .= sprintf( '<li>%1$s <span>(%2$s)</span></li>', esc_html( $row->name ), esc_html( number_format_i18n( $row->total ) ) );
    }

    return $html . '</ol>';
} );

Notes

Results are cached for 12 hours; options: [wpide_top_commenters number="5" days="90"].

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.