I was trying to build a page(template) to display my “Writing behavior” of my blog. To show which hour I post most in a day of all time, I need to calculate the “average post-time (hour) of day”, so that I could know like”uh I usually post blog in the morning…”
The first idea came to my mind is sum all “time(hours)” together, then divide them by “total post count”, then translate to 24hour format to show up, but seems my code didn’t work.
The core code I wrote is like this:
<?php
$alltimes=$wpdb->get_var($wpdb->prepare("SELECT sum(post_date) FROM $wpdb->posts WHERE post_type = 'post'", $alltimes));
echo '<p>Total post count '.$published_posts.'</p>';
$count_posts = wp_count_posts(); $published_posts = $count_posts->publish;
$averagetime= $alltimes / $published_posts;
echo '<p>Average Time count is '.$averagetime.'</p>';
echo'<p>Average time is '.date('Y-m-d h:i:s',$averagetime).'</p>';
?>
My mistake is the year,month,day,hour,sec.. all summed up to “$alltimes”, so when I divide it will become a disaster.
Maybe if I could get the “hour” in “post_date” but not the whole “post_date” will do the job, but how to?
Thank you for your time.
I think you’re looking for a query like this. I’m using
HOUR()
andDATE()
to extract the date and hour parts from the datetime value:This will show how many posts have been made during different hours of the day, notice that this only will return rows where
post_date
match the current date. If you would like to get the most hour based on all posts you just need to remove theDATE(post_date) = DATE(NOW())
condition:If you only would like to get one single row that contains the hour with the maximum number of posts, this would work:
or like this:
Reference
Mysql – Date and Time Functions