Return terms from multiple taxonomies using $wpdb

I would be the first to admit that I know next to nothing about SQL queries, but after numerous searches and some trial and error I was able to cobble together a query that returned the results I was looking for.

The problem now is I need to return the results from two taxonomies and I am not sure how to do it. This is my query that returns the results from the first taxonomy:

$wpdb->get_results(
“SELECT {$wpdb->prefix}posts.ID, {$wpdb->prefix}posts.post_title, {$wpdb->prefix}posts.post_author, {$wpdb->prefix}posts.post_date, {$wpdb->prefix}terms.name AS ‘layout_type’
FROM
{$wpdb->prefix}posts
INNER JOIN {$wpdb->prefix}term_relationships ON ( {$wpdb->prefix}posts.ID = {$wpdb->prefix}term_relationships.object_id )
INNER JOIN {$wpdb->prefix}terms ON ( {$wpdb->prefix}term_relationships.term_taxonomy_id = {$wpdb->prefix}terms.term_id )
INNER JOIN {$wpdb->prefix}term_taxonomy ON ( {$wpdb->prefix}term_relationships.term_taxonomy_id = {$wpdb->prefix}term_taxonomy.term_taxonomy_id )
WHERE
{$wpdb->prefix}posts.post_type = ‘et_pb_layout’
AND {$wpdb->prefix}term_taxonomy.taxonomy = ‘layout_type’
ORDER BY {$wpdb->prefix}posts.ID DESC”,
ARRAY_A
);

And here is the query that returns the second one:

$wpdb->get_results(
“SELECT {$wpdb->prefix}posts.ID, {$wpdb->prefix}posts.post_title, {$wpdb->prefix}posts.post_author, {$wpdb->prefix}posts.post_date, {$wpdb->prefix}terms.name AS ‘scope’
FROM
{$wpdb->prefix}posts
INNER JOIN {$wpdb->prefix}term_relationships ON ( {$wpdb->prefix}posts.ID = {$wpdb->prefix}term_relationships.object_id )
INNER JOIN {$wpdb->prefix}terms ON ( {$wpdb->prefix}term_relationships.term_taxonomy_id = {$wpdb->prefix}terms.term_id )
INNER JOIN {$wpdb->prefix}term_taxonomy ON ( {$wpdb->prefix}term_relationships.term_taxonomy_id = {$wpdb->prefix}term_taxonomy.term_taxonomy_id )
WHERE
{$wpdb->prefix}posts.post_type = ‘et_pb_layout’
AND {$wpdb->prefix}term_taxonomy.taxonomy = ‘scope’
ORDER BY {$wpdb->prefix}posts.ID DESC”,
ARRAY_A
);

How can I combine these two queries into one?

I cannot use normal WordPress commands to return these results because at the time I need them the taxonomies are not yet loaded.

Read more here:: Return terms from multiple taxonomies using $wpdb

Leave a Reply

Your email address will not be published. Required fields are marked *