如何在WooCommerce自定义模板中限制仅显示3个产品属性行
修改方案
核心思路是先收集所有非空的属性数据,再筛选出前3个进行输出,解决原代码无法控制显示数量的问题。修改后的代码如下:
add_action( 'cw_shop_page_attribute', 'cw_shop_page_attribute', 25 ); function cw_shop_page_attribute() { global $product; // 统一整理所有属性的配置:图标类、显示标题、对应WooCommerce属性键 $attributes = [ [ 'icon' => 'fa fa-desktop fa-2x', 'title' => 'Display', 'key' => 'display-size' ], [ 'icon' => 'fa fa-microchip fa-2x', 'title' => 'Processor', 'key' => 'processor-type' ], [ 'icon' => 'fa fa-camera fa-2x', 'title' => 'Rear Camera', 'key' => 'primary-camera' ], [ 'icon' => 'fa fa-camera fa-2x', 'title' => 'Front Camera', 'key' => 'secondary-camera' ], [ 'icon' => 'fa fa-hdd-o fa-2x', 'title' => 'Storage', 'key' => 'internal-storage-gb' ], [ 'icon' => 'fa fa-memory fa-2x', 'title' => 'RAM', 'key' => 'ram-gb' ] ]; $valid_attributes = []; // 筛选出值不为空的属性 foreach ( $attributes as $attr ) { $value = $product->get_attribute( $attr['key'] ); if ( !empty( $value ) ) { $attr['value'] = $value; $valid_attributes[] = $attr; } } // 只保留前3个非空属性 $display_attributes = array_slice( $valid_attributes, 0, 3 ); // 循环输出属性表格行 foreach ( $display_attributes as $attr ) { echo '<tr class="_plspcdt">'; echo '<td class="_plspcicon"><i class="' . esc_attr( $attr['icon'] ) . '"></i></td>'; echo '<td class="_atrbttl">' . esc_html( $attr['title'] ) . '</td>'; echo '<td class="_atrbvlu">' . wp_kses_post( $attr['value'] ) . '</td>'; echo '</tr>'; } }
关键修改点
- 集中管理属性:把所有属性的标识信息整合到数组,后续新增/修改属性只需调整这个数组,维护更高效。
- 筛选有效数据:通过循环过滤掉空值属性,只保留有内容的项。
- 控制显示数量:用
array_slice截取前3个有效属性,确保最多显示3行。 - 安全输出优化:使用
esc_attr、esc_html等函数处理输出内容,避免潜在的XSS安全风险。
内容的提问来源于stack exchange,提问作者user3244304
相关产品推荐
相关产品推荐

