WP-REST API excluding category doesn’t work

I used this semi-official plugin to enable API call.

But I can’t find a way to exclude category. For example if I have mysite.com/wp-json/wp/v2/posts?filter[category__not_in]=10, it will ignores the filter and show all latest posts.

Read More

Is there a way to exclude category from the API call?

Related posts

2 comments

  1. With the Rest API some filters are available only for logged in users:

    In addition, the following are available when authenticated as a user
    with edit_posts:

    […]

    category__not_in

    This is taken from the Rest API 1.0 documentation.

    What that mean is you need to logged in as an editor (user with edit_posts capability). For doing this in a clean way, I suggest create a minimal role for REST user with only the capabilities you need, something like this:

    add_role(
        'rest_user',
        __( 'REST User' ),
        array(
            'read'         => true,
            'edit_posts'   => true,
            'delete_posts' => false
        )
    );
    

    Then do your query as authenticated user with the following:

    $response = wp_remote_request('http://example.com/wp-json/wp/v2/posts?filter[category__not_in]=10', array(
        'method' => 'GET',
        'headers' => array(
            'Authorization' => 'Basic ' . base64_encode('login:password')
        )
    ));
    

    Thanks to this article you shared, it seems you need to declare the filter name as query var, so in this case:

    add_filter('query_vars', function($query_vars) {
        $query_vars[] = 'category__not_in';
        return $query_vars;
    });
    

    Which make sense because WordPress is droping any GET parameter that isn’t declare, though I don’t understand why all the filters are not declared as query vars inside the WP Core…

  2. For WP API V2 use a minus sign, for example:

    http://yourwpwebsite/wp-json/wp/v2/posts/&filter[cat]=1,2,-3
    

    will retrieve all posts in categories with id= 1 and id = 2 but excluding any posts in category with id= 3

Comments are closed.