Custom WooCommerce endpoint with dynamic value is not working

Viewed 377

I wanted to make a new endpoint for WooCommerce with dynamic value. Unfortunately I got rest_no_route error.

This is the code (plugin):

<?php 

function filter($data){
    $brand = $data['brand'];
    $products = [];
    $loop = new WP_Query( array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
        'meta_query'     => array( array(
            'key'        => 'brands.id',
            'value'      => $brand,
            'compare'    => '=',
        )),
    ));
    if ( $loop->have_posts() ){
        while ( $loop->have_posts() ){
            $loop->the_post();
            array_push($products, get_post())
        } 
        wp_reset_postdata();
    }
    return $products;
    
}

add_action( 'rest_api_init', function () {
  register_rest_route( '/wc/v3', '/brand=(?P<brand>\d+), array(
    'methods' => 'GET',
    'callback' => 'brand',
  ) );
} );


?>

This is how I try to access:

/wp-json/wc/v3/brand=1623

This is how a brand property looks like inside a product:

"brands": [
            {
                "id": 1623,
                "name": "HUGO BOSS",
                "slug": "hugo-boss"
            }
        ],

Thanks for every help!

1 Answers

This is about taxonomy terms (not post meta data) and particularly WooCommerce brands, so you need to use a tax query instead as follow (assuming that you are using WooCommerce Brands, so the taxonomy should be "product_brand").

So your function that make the WP_Query should be:

function filter($data){
    if( isset($data['brand']) && $data['brand'] > 0 ) {
        $taxonomy = 'product_brand'; // The taxonomy for WooCommerce Brands
        
        $products = (array) get_posts( array(
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'tax_query'      => array( array(
                'taxonomy'      => $taxonomy,
                'field'         => 'term_id',
                'terms'         => intval($data['brand']),
            ) ),
        ) );
        
        // return an array of WP_Post Objects (or an empty array)
        return $products; 
    }    
}

It should better work. You should name your function differently with a customized name.

Related