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

Sub*_*air 2 wordpress product variations woocommerce

我如何从自定义产品循环中获取产品版本ID。我有变异属性,例如

{ 'pa_color'=>'red','pa_size'=>'large'}
Run Code Online (Sandbox Code Playgroud)

muj*_*nly 5

匹配的属性集是

[
    'attribute_pa_color' => 'blue',
    'attribute_pa_size' => 'small',
];
Run Code Online (Sandbox Code Playgroud)

下面是我最终创建的用于实现此功能的功能:

/**
 * 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
    );
}
Run Code Online (Sandbox Code Playgroud)

  • 我只想对此答案添加一个值得注意的评论。如果您有一个具有多个属性的动态变体,并且一个或多个可以包含“ any”的值,那么您必须传入一个空白属性作为属性数组的一部分。**示例:**`((new \ WC_Product_Data_Store_CPT())-> find_matching_product_variation($ product,array('attribute_pa_style'=>'','attribute_pa_color'=>'','attribute_pa_logo'=>``,'attribute_pa_size' =>'small',)); ` (3认同)