WoocommerceWoocommerce HooksWordpressWordpress HooksWordpress TricksWp Tricks

WordPress – Custom Rest Api for Woocommerce product category filter based on product category slug

Hello to all, welcome again on therichpost.com. In this post, I will tell you, WordPress – Custom Rest Api for Woocommerce product category filter.

Post Working:

In this post, I am making WordPress rest api, with I am getting woocommerce product by category slug.

Here is the code snippet and you need to add this into your theme’s functions.php file:

add_action( 'rest_api_init', function () {
 register_rest_route( 'productfiltercat/v1', '/product/category/(?P<slug>[^/]+)', array(
    'methods' => 'GET',
    'callback' => 'therich_func',
  ) );
} );

function therich_func( $data ) {
  
  $p = wc_get_products(array('status' => 'publish', 'category' => $data['slug']));
     $products = array();
  
   
     foreach ($p as $product) {
    
    
    $products[] = $product->get_data();
    
    
     }
   
     return new WP_REST_Response($products, 200);
}

 

Here is my Rest API path:

http://localhost/wordpress/wp-json/productfiltercat/v1/product/category/category-1

 

If you have any kind of query then please do comment below.

Jassa

Thanks

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, Angular 8, Angular 9, Angular 10 Nodejs, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.