Automattic\WooCommerce\StoreApi\Utilities
CartController::get_variation_id_from_variation_data
Try to match request data to a variation ID and return the ID.
Method of the class: CartController{}
No Hooks.
Returns
Int. Matching variation ID.
Usage
// protected - for code of main (parent) or child class $result = $this->get_variation_id_from_variation_data( $request, $product );
- $request(array) (required)
- Add to cart request params.
- $product(WC_Product) (required)
- Product being added to the cart.
CartController::get_variation_id_from_variation_data() CartController::get variation id from variation data code WC 10.5.0
protected function get_variation_id_from_variation_data( $request, $product ) {
$data_store = \WC_Data_Store::load( 'product' );
$match_attributes = $request['variation'];
$variation_id = $data_store->find_matching_product_variation( $product, $match_attributes );
if ( empty( $variation_id ) ) {
$required_attributes = array_filter(
$product->get_attributes(),
function ( $attribute ) {
return $attribute->get_variation();
}
);
$selected_attributes = array_filter(
$match_attributes,
function ( $value ) {
return '' !== $value && null !== $value;
}
);
if ( count( $selected_attributes ) < count( $required_attributes ) ) {
throw new RouteException(
'woocommerce_rest_missing_attributes',
esc_html__( 'Missing attributes for variable product.', 'woocommerce' ),
400
);
}
throw new RouteException(
'woocommerce_rest_variation_id_from_variation_data',
esc_html__( 'No matching variation found.', 'woocommerce' ),
400
);
}
return $variation_id;
}