我知道我可以创建颜色、大小等属性。但由于某种原因,我不得不将 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
最后我迷路了
请帮我找到正确的方法,谢谢
尝试以下操作,应该可以达到您的预期(来自定义的 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]) );
// echo '<pre>'. print_r( $values[$type], true ) . '</pre>';
}
}
应该可以。