php - 获取变体的特定属性对应的数据值

标签 php wordpress woocommerce subscription product-variations

我正在编辑 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/

相关文章:

php - 正则表达式解析视频持续时间字符串

php - 如何在主题中包含 Redux 框架

wordpress - 如何在 WooCommerce 中获取订单 ID?

php - 在 php 中使用 Decorator 的完整继承行为

php - 使用逗号分隔值 mysql 进行搜索

swift - 我如何在 WordPress REST API(版本 2)中创建评论

wordpress - 在WordPress中进行调试

wordpress - 产品页面屏幕选项调整每页的产品数量

php - 从 WooCommerce 订单获取 protected 自定义订单项元数据数组

Php Curl 403 禁止错误