Home > How To's/Reviews > WordPress PHP Shortcodes For Yearly Post And Comment Counts

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! 🙂

 LEGAL

My posts are not to serve as a replacement for recommendations provided by licensed physicians nor do they represent the opinions of Baylor College of Medicine or its affiliated institutions. Please read this site's Disclaimer and Terms of Use for more information.

ALSO CHECK OUT  

410 Entire Directory With .htaccess

Due to an oversight with folder permissions, I was recently the victim of a massive …

 DROP A LINE

Your email address will not be published. Required fields are marked *