如何在WordPress商品卡片/概览页仅显示特定自定义商品属性?
只在商品卡片显示特定自定义属性的解决方案
你当前的代码会调用wc_display_product_attributes()输出所有产品属性,要只显示特定属性,可以通过以下两种方式实现:
方法1:自定义格式输出单个属性
适合需要自定义显示样式的场景,代码如下:
add_action( 'woocommerce_shop_loop_item_title', function(){ global $product; // 替换为你要显示的属性slug(注意WooCommerce产品属性默认带pa_前缀) $target_attr_slug = 'pa_custom_size'; $attr_value = $product->get_attribute($target_attr_slug); // 仅当属性有值时输出 if ( !empty($attr_value) ) { // 获取属性的友好名称(比如"自定义尺寸") $attr_name = wc_attribute_label($target_attr_slug); // 输出自定义结构,可根据需求修改HTML标签和类名 echo '<div class="shop-loop-custom-attr">' . esc_html($attr_name) . ': ' . esc_html($attr_value) . '</div>'; } } );
方法2:沿用原函数格式输出单个属性
如果想保持和默认属性一致的输出样式,可筛选出目标属性后再调用原函数:
add_action( 'woocommerce_shop_loop_item_title', function(){ global $product; $target_attr_slug = 'pa_custom_size'; // 替换为你的属性slug $all_attributes = $product->get_attributes(); // 筛选出目标属性 $target_attrs = array(); if ( isset($all_attributes[$target_attr_slug]) ) { $target_attrs[$target_attr_slug] = $all_attributes[$target_attr_slug]; } // 输出目标属性(格式和默认属性一致) if ( !empty($target_attrs) ) { echo wc_display_product_attributes( $product, $target_attrs ); } } );
注意事项
- 属性slug确认:在WordPress后台「产品」→「属性」中查看对应属性的slug,WooCommerce默认会给产品属性添加
pa_前缀(比如属性名称为"材质",slug可能是pa_material) - 代码添加位置:可将代码粘贴到当前主题的
functions.php文件末尾,或使用自定义代码插件(如Code Snippets)避免主题更新丢失代码 - 样式调整:可通过CSS给属性容器添加样式,比如调整字体大小、间距等
内容的提问来源于stack exchange,提问作者Ansh
相关产品推荐
相关产品推荐

