Reputation: 32602
I'm running WordPress and I'd like to write a custom query that would show a monthly archive of posts based on one specific category. I used the debug mode to find out how to get a monthly archive based on all posts, select a specific category. Here are the queries:
Get montlhy archive:
SELECT YEAR(post_date) AS `year`, MONTH (post_date) AS `month`,
count(ID) as posts FROM wp_posts
WHERE post_type = 'post' AND post_status = 'publish'
GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC
Select category:
SELECT t.*, tt.* FROM wp_terms AS t INNER JOIN wp_term_taxonomy
AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy
IN ('category') AND t.slug = 'blog' ORDER BY t.name ASC
I can't figure out how to join these two ;) Any help appreciated!
Thanks.
Update:
There's also another table involved called term_relationships, so that makes 4 tables in total. Here's an image of WordPress' database structure: http://codex.wordpress.org/images/8/83/WP_27_dbsERD.png
Anyways, here's where I'm at:
SELECT t.*, tt.*, YEAR(post_date) AS `year`, MONTH(post_date) AS `month`,
count(ID) as posts FROM wp_posts, wp_term_relationships AS tr,
wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id
WHERE tt.taxonomy IN ('category') AND t.slug = 'blog'
AND post_type = 'post' AND post_status = 'publish'
AND ID = tr.object_id AND tr.term_taxonomy_id = t.term_id
GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC
I know it's not the best way around, and that's why I need your help ;)
Thanks.
Upvotes: 1
Views: 222
Reputation: 2848
How about something like this as the basis for the joins and where clause additions that you need:
SELECT
YEAR(post_date) AS `year`,
MONTH (post_date) AS `month`,
count(ID) as posts
FROM wp_posts
INNER JOIN wp_term_relationships wtr ON wp_posts.id = wtr.object_id
INNER JOIN wp_term_taxonomy wtt ON wtr.term_taxonomy_id = wtt.term_taxonomy_id
INNER JOIN wp_terms wt ON wtt.term_id = wt.term_id
WHERE post_type = 'post' AND post_status = 'publish'
AND wtt.taxonomy = 'category'
AND wt.name = 'enter category name here'
GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC
Upvotes: 3