在 Woocommerce 产品中按类型对产品属性术语进行分类以供显示

问题描述 投票:0回答:1

我知道我可以创建颜色、大小等属性。但由于某种原因,我不得不将 3 个属性合并为一个,然后以不同的方式显示它们。

现在,我有了带有值的属性:

pa_mixed :红、蓝、绿、S、M、L、儿童、成人

但是在前端我必须显示如下:

颜色:蓝色、红色
尺寸:M
年龄 : 儿童

到目前为止我已经尝试过:

    if (!empty ($product->get_attribute('pa_mixed'))):
        $pa_mixed = $product->get_attribute('pa_mixed');
    else:
        $pa_mixed = "";
    endif;

    $size = array('S','M','L'); 
      
      if ( in_array( $size, $pa_mixed ) ) {
         //colors attributes
      }
      //etc

最后我迷路了

请帮我找到正确的方法,谢谢

php wordpress woocommerce product taxonomy-terms
1个回答
0
投票

尝试以下操作,应该可以达到您的预期(来自定义的 WC_Product 对象)

$options = $product->get_attribute('pa_mixed'); // Attribute term names set in the product (string)
$options = ! empty($options) ? explode(', ', $options) : array(); // Convert to an array

if ( ! empty($options) ) {
    // Classifying "Mixed" attribute terms
    $data    = array(
        'colors' => array('label' => __('Colors', 'woocommerce'), 'options' => array('Red', 'Blue', 'Green')),
        'size'   => array('label' => __('Size', 'woocommerce'), 'options' => array('S', 'M', 'L')),
        'aged'   => array('label' => __('Aged', 'woocommerce'), 'options' => array('Children', 'Adult')),
    );
    $types   = array('colors', 'size', 'aged'); // Defined types
    $values  = array(); // Initializing

    // Loop through the "Mixed" attributes term names set in the product
    foreach( $options as $option ) {
        foreach( $types as $type ) {
            if ( in_array($option, $data[$type]['options']) ) {
                $values[$type][] = $option;
            }
        }
    }

    // Display: Loop through classified types
    foreach( $types as $type ) {
        printf( '<div class="attribute-%s">
        <span class="label">%s :</span> <span class="options">%s</span>
        </div>', $type, $data[$type]['label'], implode(', ', $values[$type]) );
    }
}

应该可以。


为了测试目的,因为我没有你的“混合”属性设置和产品设置,所以我替换了第一行:

$options = $product->get_attribute('pa_mixed');

与:

$options = 'Blue, Red, M, Children';

我得到以下显示:

© www.soinside.com 2019 - 2024. All rights reserved.