Last active
December 17, 2015 05:09
-
-
Save RadGH/5556174 to your computer and use it in GitHub Desktop.
MySQL/Wordpress: Select number of posts by month/year/day/etc, optionally filtered by category
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Select the count of posts grouped by year, month, day, hour, even minutes and seconds! | |
SELECT | |
-- Number of posts on the specified time range | |
COUNT(*) as "count", | |
-- Time values to return | |
-- These should also be listed under "group by" | |
-- If sorting is necessary, also include these in "order by" | |
YEAR(p.post_date) as "year", | |
MONTH(p.post_date) as "month", | |
DAY(p.post_date) as "day", | |
HOUR(p.post_date) as "hour" | |
-- You only "need" wp_posts, however if looking at a specific category, the other tables should be joined | |
FROM wp_posts p | |
LEFT JOIN wp_term_relationships rel ON rel.object_id = p.ID | |
LEFT JOIN wp_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id | |
LEFT JOIN wp_terms t ON t.term_id = tax.term_id | |
-- Only look for posts categorized under category ID's 5 or 9 (optional) | |
WHERE t.term_id IN (5, 9) | |
-- This affects the grouping of count. This should reflect the SELECT statement | |
GROUP BY | |
YEAR(p.post_date), | |
MONTH(p.post_date), | |
DAY(p.post_date), | |
HOUR(p.post_date) | |
-- Sort the results so the first element is the most recent, and the last element is the oldest | |
-- To sort ASC, you should re-order these so the longest time increment comes last, instead of first | |
ORDER BY | |
YEAR(p.post_date) DESC, | |
MONTH(p.post_date) DESC, | |
DAY(p.post_date) DESC, | |
HOUR(p.post_date) DESC | |
LIMIT 100; |
Author
RadGH
commented
May 10, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment