如何通过分类术语获得产品变体ID?
例如,如果我有两个分类法及其术语:
1) Size: medium, large
2) Color: blue, green
我的产品变体:
Variation id 1: medium > blue
Variation id 2: medium > green
Variation id 3: large > blue
Variation id 4: large > green
我想获取此词语组合medium > green
的变体ID。
答案 0 :(得分:3)
以下函数使用非常简单的SQL查询从变量产品中获取已定义产品属性“颜色”和“尺寸”项的变量的变体ID:
function get_product_variation_id( $size, $color, $product_id = 0 ) {
global $wpdb;
if ( $product_id == 0 )
$product_id = get_the_id();
return $wpdb->get_var( "
SELECT p.ID
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
JOIN {$wpdb->prefix}postmeta as pm2 ON p.ID = pm2.post_id
WHERE pm.meta_key = 'attribute_pa_color'
AND pm.meta_value LIKE '$color'
AND pm2.meta_key = 'attribute_pa_size'
AND pm2.meta_value LIKE '$size'
AND p.post_parent = $product_id
" );
}
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。
用法(2个案例):
1)从已定义的变量产品ID(其中746
是父变量产品ID):
$variation_id = get_product_variation_id( 'large', 'blue', 746 );
2)在可变产品单一产品页面(无需定义可变产品ID):
$variation_id = get_product_variation_id( 'large', 'blue' );
答案 1 :(得分:1)
我还没有测试过,但是应该已经准备好了或者可以发货了。
function get_variation_by($size, $color) {
$args = array(
'post_type' => 'product',
'numberposts' => -1,
);
$product_posts = get_posts( $args );
foreach ( $product_posts as $single_product_post ) {
$_product = wc_get_product( $single_product_post->ID );
if ($product_s->product_type != 'variable') continue;
$avail_vars = $_product->get_available_variations();
foreach ($avail_vars as $v)
if ($v["attributes"]["attribute_pa_size"] == $size
&& $v["attributes"]["attribute_pa_color"] == $color)
return $v;
}
return null;
}
$variation = get_variation_by( "large", "green");
$variation_id = $variation->variation_id;
如果已经具有变量product的product_id,则可以这样简化:
function get_variation_by($variable_product_id, size, $color) {
$var_prod = wc_get_product( $variable_product_id );
$avail_vars = $var_prod->get_available_variations();
foreach ($avail_vars as $v)
if ($v["attributes"]["attribute_pa_size"] == $size
&& $v["attributes"]["attribute_pa_color"] == $color)
return $v;
return null;
}