【问题标题】:WooCommerce: Get multiple specific product attributes with attribute labelWooCommerce:使用属性标签获取多个特定产品属性
【发布时间】:2020-09-22 04:58:56
【问题描述】:

我想在产品详细信息页面上显示一组特定的产品属性。像这样:

  • 颜色:蓝色、红色
  • 尺码:M、L、XL

到目前为止,我只找到了一个代码来显示产品的每个属性:

global $product;
    $attribute = $product->get_attributes();
    
    $attribute_arr = array();
    
    if( count($attribute) > 0 ){
        foreach ($attribute as $key => $value) {
            $attribute_arr[] = $key;
        }
    }

问题是,我不想展示所有这些。只有一组特定的属性。 也许我可以使用一个数组来定义我想要显示的属性。比如:

array('pa_color', 'pa_size')

我还有一个显示特定属性的工作代码:

<?php
global $product;
$pa_colors = wc_get_product_terms( $product->get_id(), 'pa_color', array( 'fields' =>  'all', 'orderby' => 'menu_order' ) );
if( $pa_colors ) : ?>

    <ul>
        <?php foreach ( $pa_colors as $pa_color ) : ?>
        <li>
            <?php echo $pa_color->name; ?>
        </li>
        <?php endforeach; ?>
    </ul>
        
<?php endif; ?>

有没有办法将这两个代码结合起来? 我怎样才能显示属性的标签(例如颜色)?

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    您可以改用 WordPress wp_get_post_terms() 函数,如下所示:

    global $product;
    
    $attribute_taxonomies = array('pa_colors', 'pa_sizes'); // Defined product attribute taxonomies
    
    // Loop through your defined product attributes taxonomies:
    foreach ( $attribute_taxonomies as $attribute ) {
        $term_names = wp_get_post_terms( get_the_id(), $attribute, ['fields' => 'names'] );
    
        if( ! empty( $term_names ) ) {
            echo '<p><strong>' . wc_attribute_label($attribute) . ':</strong> ' . implode(', ', $term_names) . '</p>';
        }
    }
    

    经过测试并且有效。

    【讨论】:

    • 谢谢,但是当我使用var_dump 显示$term_names 的内容时,我得到了当前产品的所有属性。因为我使用的是slug,所以我使用wc_attribute_label($attribute)来获取属性的标签
    • 抱歉,如果不够清楚。当然,我想显示产品中使用的属性的所有术语名称。而且只有我在数组中选择的属性。但目前$term_names 显示每个属性及其所有内容(多个object(WC_Product_Attribute),如果这有意义的话
    • 再次感谢您!但现在我在数组中得到一个错误:["invalid_taxonomy"] :-(
    • 啊好的,我要把'pa_'.$attribute改成$attribute
    • 再次感谢!好东西;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 2019-04-04
    • 2019-01-25
    • 2019-04-30
    相关资源
    最近更新 更多