0

I'm working with woocommerce rest API v1 to build a shop page working with AJAX.

What I have tried :

  • created custom taxonomies for woocommerce products post type
  • set show_in_rest to true for those taxonomies
  • made a request to the woocommerce rest api like /wp-json/wc/v1/products/?consumer_key=[actual_consumer_key]&consumer_secret=[actual_consumer_secret]

What I expected :

A list of products and their variations with categories, tags, AND custom taxonomies, for each product.

What I got :

A list of products with everything BUT NOT my custom taxonomies

My guess :

Taxonomies bind to wordpress post while woocommerce rest api returns JSON data like a an instance WC_Product class. But if this is the case, why do I have categories and tags ? (which are default taxonomies)

I'm pulling this data with AJAX, so get_terms is not an option. I can't make one request by product to get the taxonomies, I need everything packed.

Do I need to create a custom endpoint for this ?

Please let me know if I'm not clear.

cheers,

EDIT : I have just found that the wordpress REST API (not woocommerce) enables me to retrieve custom taxonomies along with products. I have several issues with this :

  1. I don't have all products in there
  2. there isn't any info about the product like its variations, or price
  3. I don't want to make one request on both Woocommerce and Wordpress rest API to get all the data

Is the custom endpoint the only way ?

0

I eventually found a way using filters. I didn't know there were filters for REST API responses... Here is my solution :

add_filter( 'woocommerce_rest_prepare_product', 'custom_products_api_data', 90, 2 );
function custom_products_api_data( $response, $post ) {

    // retrieve a custom field and add it to API response
    $response->data['custom_taxonomy1'] = wp_get_post_terms( $post->ID, 'custom_taxonomy1', [] );
    $response->data['custom_taxonomy2'] = wp_get_post_terms( $post->ID, 'custom_taxonomy2', [] );

    return $response;

}

` Source : https://francescocarlucci.com/woocommerce-api-add-custom-data-default-endpoints/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.