omu*_*guy 6 php wordpress product variations woocommerce
我想在我的前端模板文件中显示默认的产品属性表单值和常规价格.
在var_dump
下面示出了在一个阵列的选项.我需要得到[default_attributes]
价值观.
<?php
global $product;
echo var_dump( $product );
// Need to get the [default_attributes] values
?>
Run Code Online (Sandbox Code Playgroud)
为使您可以使用一个变量产品的默认属性WC_Product
的方法get_default_attributes()
是这样的:
<?php
global $product;
if( $product->is_type('variable') ){
$default_attributes = $product->get_default_attributes();
// Testing raw output
var_dump($default_attributes);
}
?>
Run Code Online (Sandbox Code Playgroud)
现在要找出哪个是此“默认值”属性的相应产品变体,要复杂一点:
<?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();
}
}
?>
Run Code Online (Sandbox Code Playgroud)
这已经过测试并且可以工作。