How to Retrieve Related Terms Between Two Custom Taxonomies in WordPress

I’m working with two custom taxonomies in my WordPress site and need some help with a specific query. I have one taxonomy called Vehicle_Make and another called Location.

What I want to do is get all the terms from the Location taxonomy, but only show the locations that actually have posts with Vehicle_Make terms assigned to them.

I know the basic functions like get_terms('vehicle_make') and get_terms('location') work fine for getting all terms from each taxonomy. But I can’t figure out how to filter the location terms to only include those that have a relationship with the vehicle_make taxonomy through shared posts.

$locations = get_terms('location');
$vehicle_makes = get_terms('vehicle_make');
// How do I connect these two?

Is there a way to query this directly or do I need to loop through posts and check for term relationships? Any code examples would be really helpful.

You can do this with get_terms() and meta_query, but it needs a different approach. Skip the complex SQL joins and use WordPress’s built-in taxonomy queries instead.

First, use get_posts() with tax_query to grab all posts that have any vehicle_make taxonomy. Then loop through those results and call wp_get_post_terms() on each post to get the location terms. Throw the location term IDs into an array to avoid duplicates.

This keeps you in WordPress core functions and performs pretty well for most sites. You’ll end up with two queries instead of one messy join, which makes it way easier to maintain and less likely to break on different hosting setups.

Had the same issue building a car dealership site last year. Best solution I found was a custom SQL query that directly grabs location terms with vehicle_make posts attached. Use wpdb to join the term relationships and posts tables - select from wp_term_taxonomy where taxonomy = ‘location’ and term_taxonomy_id exists in wp_term_relationships where object_id also shows up in another wp_term_relationships entry for vehicle_make taxonomy. Way faster than looping through posts one by one, especially with thousands of posts. The query gets messy but beats iterating through everything. Happy to share the exact SQL if you want it - basically an inner join to find where they intersect.

have you thought about using wp_query with tax_query? it can get posts that have both taxonomies and let you fetch locations from those. it should work, but idk, i haven’t tested it in a while.