How to use filter hook posts_join for querying taxonomy terms in posts_where?

Well, after trying different things, I came up with the following.

When we use posts_join there is no need to add the prefix $wpdb-> plus the table being queried. We just need the column name. In this case, we just need name and taxonomy, like this:

BEFORE

$where .= " OR ($wpdb->term_taxonomy.taxonomy IN ('category') AND $wpdb->terms.name LIKE 'politics')";

AFTER

$where .= " OR ( taxonomy IN ('category') AND name LIKE 'politics')";

It is good to point out that as queries get more complex, aliases should be used.

Using aliases looks like this:

For posts_where hook:

$where .= " OR (wtt.taxonomy IN ('category') AND wt.name LIKE 'politics' )";

For posts_join hook:

$join .= " LEFT JOIN $wpdb->term_relationships as wtr ON ($wpdb->posts.ID = wtr.object_id) ";
$join .= " LEFT JOIN $wpdb->term_taxonomy as wtt ON (wtr.term_taxonomy_id = wtt.term_taxonomy_id) ";
$join .= " LEFT JOIN $wpdb->terms as wt ON(wtt.term_id = wt.term_id) ";

Leave a Comment