Running a site like laernogetnyt.dk where we have user registrations and post creation it’s nice as an admin to have an overview of number of posts created.

What I wanted was a list of the months in a year and the total number of posts created that month – and if no posts where created give me a zero

2015
  • December (1)
  • November (7)
  • October (8)

2014
  • December (7)
  • November (2)
  • October (12)

 

Disclaimer: I’m not a developer. I’d very much like to be better but my job is centered around UX, IA and business development. The things I build is out interrest – and I do love it.

The problem

First a thought a WP_Query and some looping would do the trick, but no luck. Maybe a direct query to the database would work.

I found half solutions like here and here but they all had some unwanted behavior. One suggestion had the number of posts from all Julys into one number, not for July 2014 and July 2015.

So a mix of standard WordPress function and a call to WP->query made this habben.


// The Callback funtion from the add widget hook
function ivp_content_stats_dashboard_widget_content() {
    // Get the year of the first post
    $from_date = preg_replace('/-.*/', '', get_posts(array(
        'posts_per_page' => -1,
        'order' => 'ASC'
    ))[0]->post_date);
	
    global $wpdb;

    // Loop through each year from blog start to today
    for ( $i = $from_date; $i <= date('Y'); $i++) {
        // Lets get some markup going wrapping each year
        echo '
'; $counts[$i] = array(); // Print the year echo '

'.$i.'

'; // Now get all posts grouped by month for each year $res = $wpdb->get_results( "SELECT MONTH(post_date) as post_month, COUNT(ID) as post_count " . "FROM {$wpdb->posts} " . "WHERE YEAR(post_date) = ".$i." AND post_type = 'post' " . "AND post_status = 'publish' " . "GROUP BY post_month ORDER BY post_date ASC", OBJECT_K ); // Count months so we can set empty months to 0 instead of leaving them out $looper = range(1, 12); $out = ''; $postCount = '0'; $len = count( $looper ); // Lets get some markup going wrapping each year foreach( $looper as $m ){ $month = date_i18n('M', mktime(0, 0, 0, $m, 1)); $height = (isset( $res[$m]) ? $res[$m]->post_count : 0)*10; $out .= ''; $out .= sprintf( '%s%d', $month, isset( $res[$m]) ? $res[$m]->post_count : 0 ); $out .= ''; $postCount++; } echo '
'.$out.'
'; echo '
'; } }

Now, I don’t like the idea of a loop with wp->query. Seems like a lot of calls to the database and a hurtig performance as a result.
The good thing about this, that it is meant for the admin dashboard for admin users only. So I’m no that concerned. But if this was for the frontend I would very much like to improve on this.

Leave a Reply

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