SQL query to extract all WordPress posts with categories

SixfootJames picture SixfootJames · Oct 25, 2012 · Viewed 18k times · Source

I need to extract all posts from my WordPress DB along with the associated categories and not sure how to write this query. I've taken a couple of stabs at it already with no joy and would appreciate the help?

EDIT: Here's what I have tried already:

SELECT post_title, wpr.object_id, wp_terms.name
FROM wp_terms
INNER JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
INNER JOIN wp_term_relationships wpr ON wpr.term_taxonomy_id = 
wp_term_taxonomy.term_taxonomy_id
INNER JOIN wp_posts ON ID = wpr.object_id
WHERE taxonomy = 'category' 
AND post_type = 'post' 
ORDER by post_title

This seems to work but it returns 1,553 where I know I only have 1343 in my DB.

EDIT: We did the same thing on another SQL query a little while ago and found that it was pulling in the revisions and other post types but thought that this was resolved using post_type = 'post'

EDIT: Upon looking at the number of categories in the DB, I come up with a total number of 216, 6 off the number if you subtract 1553 - 1343 = 216. So I think this total number of 1553 is coming from the wp_terms table which needs to be excluded and only those that are active with published posts should be shown?

EDIT: The other possibility is that each post can have multiple categories, hence the reason for having more posts (1553). So how could I separate each posts into multiple categories?

Many thanks!

Answer

SixfootJames picture SixfootJames · Nov 7, 2012

This is the final answer that worked for me.

SELECT DISTINCT
post_title
, post_content
,(SELECT meta_value FROM wp_postmeta WHERE wp_postmeta.meta_key = 'Asking Price (US\$)' AND wp_postmeta.post_id = wp_posts.ID) AS "Asking Price (US\$)"
,(SELECT group_concat(wp_terms.name separator ', ') 
    FROM wp_terms
    INNER JOIN wp_term_taxonomy on wp_terms.term_id = wp_term_taxonomy.term_id
    INNER JOIN wp_term_relationships wpr on wpr.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
    WHERE taxonomy= 'category' and wp_posts.ID = wpr.object_id
) AS "Categories"
,(SELECT group_concat(wp_terms.name separator ', ') 
    FROM wp_terms
    INNER JOIN wp_term_taxonomy on wp_terms.term_id = wp_term_taxonomy.term_id
    INNER JOIN wp_term_relationships wpr on wpr.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
    WHERE taxonomy= 'post_tag' and wp_posts.ID = wpr.object_id
) AS "Tags"
FROM wp_posts
WHERE post_type = 'post' 
ORDER BY
post_title
, post_content