本文介绍了获取与WooCommerce中默认属性值相关的产品变体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的前端模板文件中显示默认的产品属性表单值及其正常价格.
I would like to display the default product attributes form value and it's regular price in my front end template file.
下面的var_dump
显示了数组中的选项. 我需要获取[default_attributes]
值.
The var_dump
below shows options in an array. I Need to get the [default_attributes]
values.
<?php
global $product;
echo var_dump( $product );
// Need to get the [default_attributes] values
?>
推荐答案
要获取可变产品的默认属性,可以使用 WC_Product
方法 get_default_attributes()
这样:
To get the default attributes for a variable product you can use WC_Product
method get_default_attributes()
this way:
<?php
global $product;
if( $product->is_type('variable') ){
$default_attributes = $product->get_default_attributes();
// Testing raw output
var_dump($default_attributes);
}
?>
现在要找出哪个是默认"属性的相应产品变体,要复杂一点:
Now to find out which is the corresponding product variation for this "defaults" attributes, is a little more complicated:
<?php
global $product;
if( $product->is_type('variable') ){
$default_attributes = $product->get_default_attributes();
foreach($product->get_available_variations() as $variation_values ){
foreach($variation_values['attributes'] as $key => $attribute_value ){
$attribute_name = str_replace( 'attribute_', '', $key );
$default_value = $product->get_variation_default_attribute($attribute_name);
if( $default_value == $attribute_value ){
$is_default_variation = true;
} else {
$is_default_variation = false;
break; // Stop this loop to start next main lopp
}
}
if( $is_default_variation ){
$variation_id = $variation_values['variation_id'];
break; // Stop the main loop
}
}
// Now we get the default variation data
if( $is_default_variation ){
// Raw output of available "default" variation details data
echo '<pre>'; print_r($variation_values); echo '</pre>';
// Get the "default" WC_Product_Variation object to use available methods
$default_variation = wc_get_product($variation_id);
// Get The active price
$price = $default_variation->get_price();
}
}
?>
这已经过测试并且可以正常工作.
This is tested and works.
这篇关于获取与WooCommerce中默认属性值相关的产品变体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!