WordPress PHP Shortcodes For Yearly Post And Comment Counts

0

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).

Alternatively, you can run the SQL query for yearly post counts (replace the database name and year):

SELECT COUNT(*)
FROM wp_posts
WHERE YEAR(post_date) = 2018
AND post_type = 'post'
AND post_status = ‘publish’

And for the comment count (again, replacing the database name and year)

SELECT COUNT(*)
FROM wp_comments
WHERE comment_approved = 1 AND YEAR(comment_date) = 2018

Have fun! 🙂

 LEAVE A REPLY

Please enter your comment!
Please enter your name here