Last 7 Days Compared Widget
Adds a dashboard widget comparing new posts, comments and user registrations from the last seven days with the seven days before, with up and down arrows.
Opens WPIDE on
Code
add_action( 'wp_dashboard_setup', function () {
wp_add_dashboard_widget( 'wpide_last_7_days', 'Last 7 days', function () {
global $wpdb;
$stats = get_transient( 'wpide_last_7_days' );
if ( false === $stats ) {
$now = time();
$week = gmdate( 'Y-m-d H:i:s', $now - WEEK_IN_SECONDS );
$two = gmdate( 'Y-m-d H:i:s', $now - 2 * WEEK_IN_SECONDS );
$pair = function ( $sql ) use ( $wpdb, $week, $two ) {
return array_map( 'intval', (array) $wpdb->get_row( $wpdb->prepare( $sql, $week, $week, $two ), ARRAY_N ) );
};
$stats = array(
'Posts' => $pair( "SELECT SUM( post_date_gmt >= %s ), SUM( post_date_gmt < %s ) FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date_gmt >= %s" ),
'Comments' => $pair( "SELECT SUM( comment_date_gmt >= %s ), SUM( comment_date_gmt < %s ) FROM {$wpdb->comments} WHERE comment_approved = '1' AND comment_date_gmt >= %s" ),
'Users' => $pair( "SELECT SUM( user_registered >= %s ), SUM( user_registered < %s ) FROM {$wpdb->users} WHERE user_registered >= %s" ),
);
set_transient( 'wpide_last_7_days', $stats, HOUR_IN_SECONDS );
}
echo '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(100px,1fr));gap:12px">';
foreach ( $stats as $label => $values ) {
list( $current, $previous ) = array_pad( $values, 2, 0 );
$diff = $current - $previous;
$arrow = $diff > 0 ? '▲' : ( $diff < 0 ? '▼' : '—' );
$color = $diff > 0 ? '#00a32a' : ( $diff < 0 ? '#d63638' : '#646970' );
printf(
'<div style="border:1px solid #dcdcde;border-radius:4px;padding:10px;text-align:center"><div style="font-size:24px;font-weight:600">%d</div><div>%s</div><div style="color:%s;font-size:12px"><span aria-hidden="true">%s</span> %s vs previous week (%d)</div></div>',
(int) $current,
esc_html( $label ),
esc_attr( $color ),
$arrow,
esc_html( ( $diff > 0 ? '+' : '' ) . $diff ),
(int) $previous
);
}
echo '</div>';
} );
} );
Notes
Figures are cached for an hour.
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.