WooCommerce:从匹配属性中获取产品变体ID

问题描述 投票:0回答:3

我如何从自定义产品循环中获取产品变体ID。我有变化属性,如,

{ 'pa_color'=>'red','pa_size'=>'large'}
wordpress woocommerce product variations
3个回答
2
投票

要匹配的属性集

[
    'attribute_pa_color' => 'blue',
    'attribute_pa_size' => 'small',
];

下面是我为实现这个目的而创建的函数:

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

0
投票

使用产品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;
}

希望这会帮助你,让我知道结果。


0
投票

没有足够的声誉来评论,所以发布,以防它有助于某人。

我一直在使用@mujuonly's answer并且它运行得很好但是WC团队在版本3.6.0中更改了与WC_Product_Data_Store_CPT相关的内容。可能这个条目在changelog性能 - 改进了find_matching_product_variation变异查找功能的速度。 #22423与https://github.com/woocommerce/woocommerce/pull/22423有关。

似乎==在属性比较中一直是===意味着唯一需要修复它的是确保属性的传递方式与它们存储在数据库中的方式相同。根据我的理解,它与数据库中的slug字段进行比较,数据库中的slug字段似乎总是小写(字母表),因此只需将属性传递给strtolower,然后再将它们传递给@mujuonly's function就可以了。

EG

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
        );
    }
© www.soinside.com 2019 - 2024. All rights reserved.