如何在内容为空时隐藏主题定制器创建的自定义产品标签?
问题分析与解决方案
你当前的代码逻辑是新建一个自定义标签,但你要处理的是主题已经在产品页面生成好的acctab-custom_tab_0标签,所以这段代码完全没作用——主题的标签是通过自身逻辑添加的,不是你这段代码生成的,自然无法通过它控制显示隐藏。
正确处理逻辑
你需要在woocommerce_product_tabs钩子中,找到主题已添加的目标标签项,判断其内容是否为空,为空则移除:
add_filter( 'woocommerce_product_tabs', 'hide_empty_custom_product_tab', 99 ); function hide_empty_custom_product_tab( $tabs ) { // 1. 确认主题存储标签内容的方式:主题定制器设置用get_theme_mod,ACF字段用get_field // 替换成主题实际的存储键名 $tab_content = get_theme_mod( 'acctab-custom_tab_0' ); // 若为ACF字段则改为:$tab_content = get_field('acctab-custom_tab_0'); // 2. 内容为空且标签存在时,移除该标签 if ( empty( trim( $tab_content ) ) && isset( $tabs['acctab-custom_tab_0'] ) ) { unset( $tabs['acctab-custom_tab_0'] ); } return $tabs; }
关键注意事项
- 内容获取方式要对应:你之前用
get_field可能找错了存储方式——主题定制器的设置通常用get_theme_mod获取,而非ACF的get_field,这会导致判断逻辑失效,标签一直显示。 - 钩子优先级要足够高:设置
99是为了确保你的代码在主题添加标签之后执行,才能修改已生成的tabs数组。 - 确认标签ID:如果主题在
$tabs数组中的标签键名不是acctab-custom_tab_0,可以在函数里加var_dump($tabs)输出查看具体结构,替换成实际键名。
备选方案(钩子方式无效时)
如果主题是硬编码输出标签,不通过woocommerce_product_tabs钩子,可使用CSS/JS隐藏:
CSS 方式
/* 隐藏空内容的标签面板及对应按钮 */ .rey-summaryAcc-item--custom_tab_0:has(>.__inner:empty), .rey-summaryAcc-accItem[href="#acctab-custom_tab_0"] { display: none !important; }
JS 方式
document.addEventListener('DOMContentLoaded', () => { const tabPanel = document.getElementById('acctab-custom_tab_0'); const tabButton = document.querySelector('.rey-summaryAcc-accItem[href="#acctab-custom_tab_0"]'); const hasContent = tabPanel.querySelector('.__inner').textContent.trim() !== ''; if (!hasContent) { tabPanel.style.display = 'none'; tabButton.style.display = 'none'; } });
内容的提问来源于stack exchange,提问作者dyz
相关产品推荐
相关产品推荐

