wordpresswoocommercewordpress-rest-apiwoocommerce-rest-apiheadless-cms

add termmeta field to woocommerce attribute in rest api result


I have woo variation swatches plugin on my website and I want to use woocommerce and wordpress in a headless project. my problem is when I want to fetch attribute terms via

/wp-json/wc/v3/products/attributes/COLOR_ATTRIBUTE_ID/terms

the returned result doesn't include the color code field. I know the color code is stored in termmeta table with product_attribute_color key. is there any way to add this meta as a field to the attributes result in rest API?


Solution

  • You can extend with woocommerce_rest_prepare_(taxonomy) hooks like this -

    add_filter( 'woocommerce_rest_prepare_pa_color', 'add_custom_data_to_product_attributes_terms', 10, 3 ); // where "taxonomy" = "pa_color" as taxonomy name
    
    // filter the product response here
    function add_custom_data_to_product_attributes_terms( $response, $post, $request ) {
        
        // $response->data['color-code'] = $response->data['description'];
        // execute all here
        
        return $response;
    }