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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.