首页 > 解决方案 > WooCommerce:从匹配属性中获取产品变体 ID

问题描述

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

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

标签: wordpresswoocommerceproductvariations

解决方案


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

推荐阅读