Query All Posts that are in More than One Category

Posted on

By Michael Fields

The following query will return all posts that are associated with more than one category. This query could be useful in the scenario where you would want to migrate a site to a category structure where each post is only assigned to one category. If this is your goal, you may want to check out my Radio Categories Plugin

$posts = $wpdb->get_results( "
	SELECT p.*, COUNT( p.`ID` ) AS 'category_count'
	FROM $wpdb->posts AS p, $wpdb->term_taxonomy as tt, $wpdb->term_relationships as tr
	WHERE tt.`taxonomy` = 'category'
	AND tt.`term_taxonomy_id` = tr.`term_taxonomy_id`
	AND tr.`object_id` = p.ID
	AND p.`post_type` = 'post'
	GROUP BY p.`ID`
	HAVING COUNT( p.`ID` ) > 1
	ORDER BY COUNT( p.`ID` ) DESC
	" );

Share your thoughts

Fork me on GitHub