我正在编辑 variable-subscription.php 文件以尝试显示特定的 WooCommerce 变量订阅属性以及某些属性数据。到目前为止,这是我的代码,您可以看到我正在尝试显示属性名称以及变体图像和描述。
<?php
// get all variations
$variations = $product->get_available_variations();
// get shirt values
$shirt_values = get_the_terms( $product_id, 'pa_shirt');
// for each shirt value
foreach ( $shirt_values as $shirt_value ) { ?>
<h1>
<?php // name
echo echo $shirt_value->name;
?>
</h1>
<?php // description
foreach ( $variations as $variable_array ){
$variation = new WC_Product_Variation( $variable_array['variation_id'] );
echo $variation->variation_description;
}
?>
<?php // image
foreach ( $variations as $variation ) { ?>
<img src="<?php echo $variation['image_src']; ?>">
<?php }
?>
目前,我有 3 件衬衫待售(在自定义产品属性中定义),然后我有几种变体。问题是这个 PHP 显示了每件衬衫的所有可能的描述/图像变体,而我只想显示与每个特定衬衫属性相关的变体。
最佳答案
您需要将方法与类 WC_Product_Variation 一起使用 get_variation_attributes()这将返回一组属性及其值对于此变体。
因此,对于属性 pa_shirt
,显示特定变体值的代码将是:
$variations = $product->get_available_variations();
// Here we use our method to get the array of attribute values for the variation
$variation_attribute = $variation->get_variation_attributes();
// Here is the value for this variation and "pa_shirt" attribute
$variation_attrib_shirt_value = $variation_attribute['attribute_pa_shirt'];
As you can notice the attributes keys slugs in the array have all
'attribute_'
in the beginning.
关于php - 获取变体的特定属性对应的数据值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42426345/