Soham Pandya
Soham Pandya

Reputation: 396

get category with parent 0 in woocommerce rest api

I am getting all categories by calling following function

$wc_api = new WC_API_Client( $consumer_key, $consumer_secret, $store_url );
echo json_encode( $wc_api->get_categories());

which is calling following function

public function get_categories( $params = array() ) {
    return $this->_make_api_call( 'products/categories', $params );
}

I want to add condition or parameter like want to get categoris which have parent = 0 how can i get it ?

Upvotes: 0

Views: 2239

Answers (2)

Ankit Prajapati
Ankit Prajapati

Reputation: 455

I recently tried this and it actually worked so some who is looking for this solution right now, so i am answering this.

Just pass parent=0 parameter and you will only get parent categories

https://yourdomain.com/wp-json/wc/v3/products/categories?per_page=25&page=1&parent=0

Upvotes: 2

Anand Shah
Anand Shah

Reputation: 14913

There are 2 ways to achieve what you are wanting:

1.Client side filtering - you are already calling get_categories function, this will return all the categories which you can then filter on the client.

2.Server side filtering - you can use woocommerce_api_product_categories_response filter to modify the API output. Add the following code to functions.php

add_filter( 'woocommerce_api_product_categories_response', 'my_woocommerce_api_product_categories_response', 10, 3);

function my_woocommerce_api_product_categories_response( $product_categories, $terms, $fields ) {

    // add your code to do the filtering here    

    return $product_categories;
}

Upvotes: 1

Related Questions