隐藏自定义短代码中值为空的WooCommerce产品属性
隐藏自定义短代码中值为空的WooCommerce产品属性
嘿,我懂你的困扰!现在你的短代码不管属性有没有值都会输出对应的行,确实影响页面整洁。咱们可以通过修改代码,只保留有实际内容的属性行,具体方案如下:
核心思路是先检查每个属性的值是否非空,只有当属性存在有效内容时,才生成对应的HTML行,这样就能自动隐藏空值的属性啦。
修改后的完整代码如下:
// Display grouped attributes Gewicht en Omvang function get_product_attributes_gewicht_shortcode( $atts ) { // 提取短码参数,默认使用当前产品ID extract( shortcode_atts( array( 'id' => get_the_ID(), ), $atts, 'display-attributes-gewicht' ) ); global $product; // 如果全局产品对象无效,通过ID获取产品实例 if ( ! is_a($product, 'WC_Product') ) { $product = wc_get_product( $id ); } // 确认产品对象有效后再处理属性 if ( is_a($product, 'WC_Product') ) { // 获取各个属性值 $gewicht = $product->get_attribute( 'Gewicht (gram)' ); $hoogte = $product->get_attribute( 'Hoogte (mm)'); $lengte = $product->get_attribute( 'Lengte (mm)'); $breedte = $product->get_attribute( 'Breedte (mm)'); // 初始化存储属性行的变量 $attribute_rows = ''; // 逐个检查属性,非空则添加对应行 if ( !empty($gewicht) ) { $attribute_rows .= '<div class="divTableAttRow">' . '<div class="divTableAttCell">Gewicht (gram)</div>' . '<div class="divTableAttCell">' . esc_html($gewicht) . '</div>' . '</div>'; } if ( !empty($hoogte) ) { $attribute_rows .= '<div class="divTableAttRow">' . '<div class="divTableAttCell">Hoogte (mm)</div>' . '<div class="divTableAttCell">' . esc_html($hoogte) . '</div>' . '</div>'; } if ( !empty($lengte) ) { $attribute_rows .= '<div class="divTableAttRow">' . '<div class="divTableAttCell">Lengte (mm)</div>' . '<div class="divTableAttCell">' . esc_html($lengte) . '</div>' . '</div>'; } if ( !empty($breedte) ) { $attribute_rows .= '<div class="divTableAttRow">' . '<div class="divTableAttCell">Breedte (mm)</div>' . '<div class="divTableAttCell">' . esc_html($breedte) . '</div>' . '</div>'; } // 只有存在属性行时才返回完整容器,避免空div if ( !empty($attribute_rows) ) { return '<div class="divTableAtt LichtBlauweRegels">' . '<div class="divTableAttBody">' . $attribute_rows . '</div>' . '</div>'; } else { // 若没有任何属性有值,返回空(也可以改成自定义提示文字) return ''; } } // 产品无效时返回空 return ''; } add_shortcode( 'display-attributes-gewicht', 'get_product_attributes_gewicht_shortcode' );
几个关键优化点:
- 使用
!empty()函数判断属性值是否存在有效内容,确保空值属性不会被输出 - 新增
$attribute_rows变量单独存储属性行,最后再组合到外层容器中,逻辑更清晰 - 增加了外层容器的判断:如果没有任何属性行,就不输出空的表格容器,进一步优化页面结构
- 用
esc_html()转义属性值,避免潜在的XSS安全问题,这是WooCommerce开发的最佳实践
这样修改后,你的短代码就只会显示有实际数据的产品属性啦!
备注:内容来源于stack exchange,提问作者John Roeland
相关产品推荐
相关产品推荐

