Question

All around the Interwebs I see advice from people who say that when you want to get posts in a custom taxonomy you should use the filter parameter, for example:

https://example.com/wp-json/wp/v2/posts?filter[genre]=fiction

This seems like a very handy parameter. But in v2 of the WP REST API it just doesn't work. When I created a WP Trac ticket to find out what was going on, @swissspidy responded that "the filter param has been removed on purpose" but that the documentation hasn't been updated yet. The change is discussed in Trac ticket 38378.

OK, fair enough, but could someone tell me how I should retrieve posts in a custom taxonomy now? I'm writing a plugin that depends on being able to do this.

For example, if I've created a non-hierarchical custom taxonomy instance and given it the value 1 for certain posts in a custom post type, how can I retrieve all the posts of that type and with instance=1?

If it's not possible via the REST API, is there a way to do it via the WordPress.com API on a Jetpack-enabled self-hosted site?

Was it helpful?

Solution

Since WordPress 4.7 the filter argument for any post endpoint was removed. But if you need them, add them via plugin. The WP API Repo have a plugin 'Rest Filter' for this job, small and short.

OTHER TIPS

The WordPress REST API documentation has a section on registering custom posts and taxonomies with the API. Essentially, you add 'show_in_rest' => true when registering the custom post type or custom taxonomy.

register_taxonomy('instance', ['post'], [
    <other args...>,
    'show_in_rest' => true,
]);

Once that's done, you can filter any object for which you registered that taxonomy ('post' in the above example) by that custom taxonomy by using its name as a query string parameter, e.g.:

https://example.com/wp-json/wp/v2/posts?instance=1

Note that the value of the taxonomy parameter ('1' in the above example) has to be the id of the taxonomy object, not it's name or slug. If you only know the slug, and not the id, you can first lookup the id by separately querying for it, because registering your custom taxonomy with the API also creates its own custom endpoint:

https://example.com/wp-json/wp/v2/instance?slug=foo-bar
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top