Creating a Relationship between two Wordpress Taxonomies

5.8k views Asked by At

Apologies if this seems like a simple question. I am developing into a system that has set up two taxonomy categories that are assigned within each post.

i.e. Products (tshirt, coat, dress etc) and Colours (black, white, red etc)

I am trying to create a search feature that will allow me to sort through each of the posts on the page (possibly using ajax) by creating a relationship between the two taxonomies that exist in each post: (products and colours)

I have looked at the meta option, however, the entire website is already working on the functionality that has been set up.

I have searched high and low on google and no idea where to start to create a relationship between the products and colours so that. It seems like it should be a relatively simple thing to do, but was hoping for the best practice of this with a wordpress theme.

thanks in advance

1

There are 1 answers

1
Mathew Tinsley On

Taxonomies are a relationship between posts, there is no way to create a defined, persistent relationship between two taxonomies.

If you need to get posts related by mutliple taxonomies, you can use a tax_query. From the documentation:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'movie_genre',
            'field'    => 'slug',
            'terms'    => array( 'action', 'comedy' ),
        ),
        array(
            'taxonomy' => 'actor',
            'field'    => 'term_id',
            'terms'    => array( 103, 115, 206 ),
            'operator' => 'NOT IN',
        ),
    ),
);
$query = new WP_Query( $args );

You can also filter a query to inject the taxonomy query. See this answer: https://wordpress.stackexchange.com/a/35263/69793