[WordPress Tips]: How to count number of posts between specific dates by a contributor ?

Updated on September 2, 2017

Recently in my WordPress installation, was trying to find out the no. of posts by a contributor between specific dates to calculate the amount to be paid for the contributor and unfortunately couldn’t find it anywhere ! I could only find out the total no. of posts by the contributor from the admin page or had to do manually from the list of posts. And for my astonishment, i couldn’t find any plugin too (Am bit hesitant in installing plugins as it loads many unnecessary scripts which increases my website loading time). So i coded few lines of PHP code to achieve the above which i would be sharing with you in case if you are looking for one such solution.

We would be doing this out of WordPress directory, just to keep it simple. You need to know “how to use WordPress functions outside the WordPress directory“, as we would be referring some of the WordPress functions.

Wordpress tips and Tricks
WordPress tips and Tricks

Create HTML5 form :

Create a HTML5 form with inputs being from and to dates, wordpress user id (if specific) and a submit button as shown below :

<form method="post">
From : <input type="date" name="from">
To : <input type="date" name="to">
User :<input type="text" name="user-id">
<input type="submit" name="submitbtn">
</form>

In case if you have a large no. of contributors and wouldn’t know their user-id’s then the best solution is to make the contributor list as drop down using Wordpress function wp_dropdown_users :

<form method="post">
From : <input type="date" name="from">
To : <input type="date" name="to">
User :<?php wp_dropdown_users( $args ); ?>
<input type="submit" name="submitbtn">
</form>

Backend Database process :

Once the form is submitted, with inputs being from & to dates and the user-id, make an SQL query to get the count of posts by the contributor being user-id, between from and to dates with status published as shown in the below code :

<?php
$from = $_POST['from'];
$to = $_POST['to'];
$user = $_POST['user'];
print "From" . $from . "\n";
print "To" . $to . "\n";
print "User" . $user . "\n";
$query = "select count(*) from wp_posts where post_author='$user' AND post_type='post' AND post_status='publish' AND post_date >= '$from' AND post_date <= '$to'";
$result = mysql_query($query) or die('Could not query:' . mysql_error());
$count = mysql_fetch_array($result);
echo "Number of posts " . $count[0]; // outputs third employee's name
?>

Print the result of the SQL query in user readable format which you can see from the below demo link :

Was this article helpful?

Related Articles

Leave a Comment