Aggregate and sort WordPress data with MySQL GROUP BY and ORDER BY

Count and group WordPress data with GROUP BY

How many posts has each author written? How many posts are in each category? How many posts were published per month? These questions are answered by SQL aggregate functions (COUNT, SUM, MAX) with GROUP BY, run in phpMyAdmin, with WP-CLI or with $wpdb.

Problem: You need statistics from the WordPress database: posts per author, per category and per month, and only the categories with more than five posts.

Solution: Group the rows with GROUP BY, count them with COUNT(), filter the groups with HAVING and sort with ORDER BY. Join the term tables for categories.

The examples use the wp_ prefix; replace it with the prefix of your site.

Posts per author

SELECT u.display_name, COUNT(*) AS posts
FROM wp_posts p
JOIN wp_users u ON u.ID = p.post_author
WHERE p.post_type = 'post' AND p.post_status = 'publish'
GROUP BY u.ID, u.display_name
ORDER BY posts DESC;

Posts per category

SELECT t.name AS category, COUNT(*) AS posts
FROM wp_terms t
JOIN wp_term_taxonomy tt     ON tt.term_id = t.term_id AND tt.taxonomy = 'category'
JOIN wp_term_relationships r ON r.term_taxonomy_id = tt.term_taxonomy_id
JOIN wp_posts p              ON p.ID = r.object_id AND p.post_type = 'post' AND p.post_status = 'publish'
GROUP BY t.term_id, t.name
ORDER BY posts DESC;

The count column of wp_term_taxonomy already holds this number, but only for published posts and only as WordPress last calculated it; counting yourself is the way to check it or to count other statuses.

Posts per month

SELECT DATE_FORMAT(post_date, '%Y-%m') AS month, COUNT(*) AS posts
FROM wp_posts
WHERE post_type = 'post' AND post_status = 'publish'
  AND post_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
GROUP BY month
ORDER BY month;

Filtering groups with HAVING

WHERE filters rows before grouping, HAVING filters the groups after counting:

SELECT t.name, COUNT(*) AS posts
FROM wp_terms t
JOIN wp_term_taxonomy tt     ON tt.term_id = t.term_id AND tt.taxonomy = 'category'
JOIN wp_term_relationships r ON r.term_taxonomy_id = tt.term_taxonomy_id
GROUP BY t.term_id, t.name
HAVING posts > 5
ORDER BY posts DESC;

The same in PHP

<?php
global $wpdb;

$rows = $wpdb->get_results( $wpdb->prepare(
    "SELECT post_author, COUNT(*) AS posts
     FROM {$wpdb->posts}
     WHERE post_type = %s AND post_status = 'publish'
     GROUP BY post_author
     ORDER BY posts DESC",
    'post'
) );

NOTE: Since MySQL 5.7 the default ONLY_FULL_GROUP_BY mode requires every selected column to be either in GROUP BY or inside an aggregate function. A query that worked on an old server can fail on a new one with “Expression #1 of SELECT list is not in GROUP BY clause”; add the column to GROUP BY (as with u.display_name above) instead of switching the mode off.