WooCommerce: Get Product Variation ID from Matching Attributes

会有一股神秘感。 提交于 2019-12-10 11:06:09

问题


How I get product variation id from custom product loop. I have variation attribute like,

{ 'pa_color'=>'red','pa_size'=>'large'}

回答1:


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
    );
}



回答2:


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
        );
    }



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!