REST API and Woodmart Variations As Single Products Setting
-
Hello,
We are using the WooCommerce REST API (wp-json/wc/v3/products) to retrieve products from our store. However, due to a setting for variable products (https://prnt.sc/vOquuiZUP36Z), which we need to display variations as individual products, the API response is also altered and shows variations as separate products, similar to how they appear on the website. I want to restrict this behavior so that the WooCommerce REST API functions normally, while still maintaining this setting for the website. Could you please guide us on how to achieve this, or if necessary, apply the fix to the main theme?
Thanks
Hello,
Try to add the following PHP code snippet to the child theme functions.php file to fix this
add_filter(
'woocommerce_rest_prepare_product_object',
function ( $response, $object, $request ) {
if ( 'variation' === $object->get_type() ) {
return;
}
return $response;
},
10,
3
);
Kind Regards
Hello,
Ok thank you we have tried the code but it is completely removing variation products from the API response. In the API response we need variable products instead of variations.
Can this be achieved?
LP
Hello,
Try to replace the old code with this one
add_action(
'init',
function() {
if ( ! woodmart_get_opt( 'show_single_variation' ) ) {
return;
}
$query = XTS\Modules\Show_Single_Variations\Query::get_instance();
if ( has_action( 'pre_get_posts', array( $query , 'add_variations_to_product_query') ) ) {
remove_action( 'pre_get_posts', array( $query , 'add_variations_to_product_query') );
}
}
);
Kind Regards
Hello,
That seems to be working – thank you you guys are great!
One thing that seems to have changed with the code addition is that we can’t choose individual variations for elements like Elementors ‘Edit Products (grid or carousel) where the list of ids selection box now only shows the parent and not the variation products to be selected. See image attached.
Regards
LP
Attachments:
You must be
logged in to view attached files.
Hello,
Try to replace the following line
if ( ! woodmart_get_opt( 'show_single_variation' ) ) {
with this one
if ( ! function_exists( 'wc' ) || ! woodmart_get_opt( 'show_single_variation' ) || ! wc()->is_rest_api_request() ) {