WordPress Rest filter for custom taxonomy gets applied to the admin area

I’m using gutenberg… could that be the reason?

Yes, Gutenberg (or the Block Editor) uses the WordPress REST API when working with the taxonomy terms (and other things like custom post types).

So the filter rest_collection_query (or rest_{taxonomy}_query) will be applied no matter who/what made the REST API request, or where it was being made from (e.g. was it via /wp-admin/ or the site front-end?).

I’m using wordpress API

Assuming that you’re making manual requests to the “collection” taxonomy endpoint (/wp-json/wp/v2/collection), you can distinguish the request’s origin by using a custom parameter like so where the parameter name is my_key — and if the value is 1, then we can filter the $args (i.e. the query parameters):

add_filter( 'rest_collection_query', function( $args, $request ){
    if ( '1' === $request->get_param( 'my_key' ) ) {
        // your code here
    } // else, don't filter/modify $args

    return $args;
}, 10, 2 );

And then for example using the window.fetch() in JavaScript, you could do something like:

window.fetch( '/wp-json/wp/v2/collection?per_page=2&my_key=1' )
    .then( res => res.json() )
    .then( terms => console.log( terms ) );

Alternate Solution

Add your own custom endpoint and do whatever your heart desires..

The Classic Editor may help, but if a plugin or custom code performs a request to the exact same “collection” taxonomy endpoint, then you know what could happen. 😉

Last but not least..

By default, is_admin() returns false on a REST API endpoint/URL. So if for example you’re on http://example.com/wp-json/wp/v2/posts (or that you make API request to that endpoint), then:

if ( ! is_admin() ) {
    // code here runs
}

Leave a Comment

deneme bonusudeneme bonusu veren sitelerpulibet girişOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino