如何在WordPress中使用短代码添加多个产品属性
实现WordPress产品页面多属性显示的短代码优化
你可以修改现有代码,让短代码支持传入多个属性名称(用逗号分隔),循环输出每个属性内容,具体代码如下:
// 短代码:输出多个产品属性 function product_list_attribute_func( $atts ){ global $product; // 设置默认属性,支持多属性逗号分隔 $atts = shortcode_atts( array( 'name' => 'processor', ), $atts ); // 将属性名称字符串转为数组 $attribute_names = array_map('trim', explode(',', $atts['name'])); $output = ''; // 循环遍历每个属性并获取内容 foreach( $attribute_names as $name ){ if( is_string( $name ) && !empty($name) ){ $prod_attribute = $product->get_attribute( $name ); // 仅当属性有内容时才输出,可自定义格式 if( !empty($prod_attribute) ){ $output .= '<div class="product-attribute-item">'; $output .= '<span class="attribute-label">' . ucfirst($name) . ':</span> '; $output .= '<span class="attribute-value">' . $prod_attribute . '</span>'; $output .= '</div>'; } } } return $output; } add_shortcode('product_list_attribute', 'product_list_attribute_func');
使用说明
在产品页面或内容中,通过逗号分隔传入多个属性名称即可:
[product_list_attribute name="processor,ram,storage,screen-size"]
关键修改说明
- 将传入的
name参数按逗号分割为数组,支持多属性批量处理 - 增加循环遍历每个属性,逐一获取并输出内容
- 添加基础HTML结构,方便后续通过CSS自定义样式(可根据需求调整格式)
- 增加非空判断,避免输出空内容
内容的提问来源于stack exchange,提问作者Nishit Agrawal
相关产品推荐
相关产品推荐

