How I get product variation id from custom product loop. I have variation attribute like,
{ 'pa_color'=>'red','pa_size'=>'large'}
Set of attributes to match are
[
'attribute_pa_color' => 'blue',
'attribute_pa_size' => 'small',
];
Below is the function I ended up creating to achieve this:
/**
* Find matching product variation
*
* @param $product_id
* @param $attributes
* @return int
*/
function find_matching_product_variation_id($product_id, $attributes)
{
return (new \WC_Product_Data_Store_CPT())->find_matching_product_variation(
new \WC_Product($product_id),
$attributes
);
}
Don't have enough reputation to comment so posting instead in case it helps someone.
I have been using @mujuonly's answer and it works great however the WC team changed something related to WC_Product_Data_Store_CPT
in version 3.6.0. Likely this entry in the changelog Performance - Improved speed of the find_matching_product_variation
variation lookup function. #22423 relating to https://github.com/woocommerce/woocommerce/pull/22423.
Seems ==
has been ===
in the attribute comparison meaning the only thing required to fix it is to ensure that the attributes are passed in the same way that they are stored in the database. From what I understand it's comparing against the slug field in the database which always seems to be lowercase (where alphabetic) so simply passing your attributes through strtolower
before passing them to @mujuonly's function does the trick.
e.g.
function get_variation_id_from_attributes( $product_id, $size, $color ) {
$color = strtolower($color);
$size = strtolower($size)
$variation_id = find_matching_product_variation_id ( $product_id, array(
'attribute_pa_color' => $color,
'attribute_pa_size' => $size
));
return $variation_id;
}
function find_matching_product_variation_id($product_id, $attributes)
{
return (new \WC_Product_Data_Store_CPT())->find_matching_product_variation(
new \WC_Product($product_id),
$attributes
);
}
Try this code by using product id
/* Get variation attribute based on product ID */
$product = new WC_Product_Variable( $product_id );
$variations = $product->get_available_variations();
$var_data = [];
foreach ($variations as $variation) {
if($variation[‘variation_id’] == $variation_id){
$var_data[] = $variation[‘attributes’];
}
}
/*Get attributes from loop*/
foreach($var_data[0] as $attrName => $var_name) {
echo $var_name;
}
Hope this will help you and let me know the result.
来源:https://stackoverflow.com/questions/53958871/woocommerce-get-product-variation-id-from-matching-attributes