Rest Api How to get results of child categories with one api call

Example:

If I have a parent category 1 with child categories 2,3,4 etc

instead of a call like this:

/wp/v2/posts?categories=1,2,3,4

i want a call like this (imaging code)

/wp/v2/posts?categories=1includeallchilds=true

that will include all articles from the child and sub-child of 1.

how is this possible? I don't want my application make 2 api calls to find all childs of the categories of 1..

this query can done what i need, but i cant include this on rest api call,

$args = array(
    'post_type' = 'post',
    'order' = 'DESC',
    'posts_per_page' = 100,
    'tax_query' = array(
        array(
            'taxonomy' = 'category',
            'field'    = 'term_id',
            'terms'    = '1',
        ),
    ),
);

Topic rest-api plugin-development query-posts Wordpress

Category Web


WP can already do this out of the box thanks to the include_children parameter of tax_query which is true by default.

While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms.

Here's an example taken from the official Make WP blog, just do something like this:

const query = {
    categories: {
        terms: [ 3, 5, 7 ],
        include_children: true,
    },
};
wp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } );

Which generates a URL that looks like this:

/wp-json/wp/v2/posts?categories[terms][0]=3&categories[terms][1]=5&categories[terms][2]=7&categories[include_children]=true&_locale=user

Notice


Just stumble on this because I was looking for the solution to same issue. Don't know if it was changed but it no longer works (if ever was). Now, you have to make call to categories endpoint /categories?parent="parent_cat_id" in order to get list of child categories, then feed that info into another call (posts) /posts?categories="1,2,3,4.."&...

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.