WordPress PHP Shortcodes For Yearly Post And Comment Counts

I wanted an easy way to calculate some end-of-year stats, so I put together a two shortcodes which query the WordPress SQL database and return the number of posts and comments in the last year. Simply add the following snippet in the body of your theme’s functions.php file.

function postCountYearFunc()
{
	global $wpdb;
	$query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND post_date BETWEEN '2016-01-01' AND '2017-01-01'";
	return $wpdb->get_var($query);
}
add_shortcode( 'postCountYear', 'postCountYearFunc' );

function commentCountYearFunc()
{
	global $wpdb;
	$query = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1' AND comment_date BETWEEN '2016-01-01' AND '2017-01-01'";
	return $wpdb->get_var($query);
}
add_shortcode( 'commentCountYear', 'commentCountYearFunc' );

As the code is written, the [postCountYear] and [commentCountYear] shortcodes will display the total number of posts and comments from January 1, 2016 to January 1, 2017. Adjust the portion of code that reads ‘2016-01-01’ AND ‘2017-01-01’ to whatever interval you want (in the yyyy-mm-dd format).

Have fun! 🙂

You might also like

Leave A Reply

Your email address will not be published.