NetSpud
NetSpud

Reputation: 67

Filter WP REST API by taxonomy value (value1, value2, value3 etc...)

I'm trying to filter my Custom post type taxonomy by values, but I haven't had any success.

I wondered if anyone else knew how to you'd go about doing this, or maybe I'm taking the wrong approach here?

Thanks

Upvotes: 1

Views: 2079

Answers (2)

ZecKa
ZecKa

Reputation: 2934

Are you trying to filter your custom post type by taxonomy term value? For example you have a post type "book" and a taxonomy "book_cat", and you want to get all book from a particular book_cat, is that right?

WP REST API support filter by taxonomy term IDs natively.

You can juste make a GET request like that

https://example.com/wp-json/wp/v2/book?book_cat=20

If you need to select more than one term, separate them with a comma.

https://example.com/wp-json/wp/v2/book?book_cat=20,21,22

(https://example.com/wp-json/wp/v2/<post_type>?<taxonomy_name>=<term_id>,<term_id>)

that's it

edit: actually you cant filter post type by term slug, you need to use id

If you need to get term_id by term_slug you can do like that:

$term = get_term_by('slug', 'my-term-slug', 'my_taxonomy')
$term_id = $term->term_id;

You can use custom filter to use term slug as parameter

If you really need to use slug as url parameter you can add a custom filter, take a look to rest_{$this->post_type}_query hook

You can do something like that:

/**
 * Filter book post type by book_cat slug
 *
 * @param array $args
 * @param WP_Rest_Request $request
 * @return array $args
 */
function filter_rest_book_query( $args, $request ) { 
    $params = $request->get_params(); 
    if(isset($params['book_cat_slug'])){
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'book_cat',
                'field' => 'slug',
                'terms' => explode(',', $params['book_cat_slug'])
            )
        );
    }
    return $args; 
}   
// add the filter 
add_filter( "rest_book_query", 'filter_rest_book_query', 10, 2 ); 

and then

https://example.com/wp-json/wp/v2/book?book_cat_slug=slug01,slug02

Upvotes: 3

Rahul Sathvara
Rahul Sathvara

Reputation: 89

You can pass tax_query in your post query like this:

$tax_query[] =  array(
'taxonomy' => 'product_cat',
'field' => 'tag_ID', // Filter by Texonomy field name tag_ID
'terms' => $termID, // your texonomy by which you want to filter
);
$args = array(
    'post_type'     => 'product',
    'post_status'   => 'publish',
    'tax_query'     => $tax_query,
);

$loop = new WP_Query($args);

Also you can filter by taxonomy slug:-

$tax_query[] =  array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $slugID

);

Upvotes: -1

Related Questions