You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:WooCommerce商品页按库存状态控制tc-row显示/隐藏

解决WooCommerce中根据商品状态控制TM Extra Product Options区块显示的问题

下面提供两种可行的PHP代码方案,你可以根据需求选择:

方案1:通过动态CSS控制显示(简单直接)

这种方法通过在页面头部插入条件CSS,当商品为现货时隐藏tc-row区块,代码添加到子主题的functions.php中:

add_action('wp_head', 'hide_tc_row_based_on_stock_status');
function hide_tc_row_based_on_stock_status() {
    // 仅在单个商品页面生效
    if (!is_product()) return;

    global $product;
    if (!$product) return;

    // 判断商品库存状态:现货且非预售时隐藏区块
    $is_instock_not_backorder = ($product->get_stock_status() === 'instock') && !$product->is_on_backorder();
    
    if ($is_instock_not_backorder) {
        echo '<style>.tc-row { display: none !important; }</style>';
    }
}

代码说明

  • 仅在单个商品页面执行逻辑,避免影响其他页面
  • 核心判断:商品库存状态为instock且**未处于预售(on-backorder)**时,插入CSS隐藏tc-row
  • !important用于确保样式优先级高于插件默认样式

方案2:通过插件钩子直接不渲染字段(更彻底)

如果不想让tc-row的HTML代码出现在页面中,可以用TM Extra Product Options的钩子过滤字段渲染,需要先确认tc-row对应的字段名称(可通过浏览器开发者工具查看字段的name属性):

add_filter('tm_extra_product_options_pre_render_field', 'filter_tc_row_rendering', 10, 2);
function filter_tc_row_rendering($render_field, $field_data) {
    // 替换成你实际的tc-row字段name值
    if ($field_data['name'] !== 'tc-row') return $render_field;

    global $product;
    if (!$product) return $render_field;

    $is_instock_not_backorder = ($product->get_stock_status() === 'instock') && !$product->is_on_backorder();
    
    // 现货时阻止字段渲染
    if ($is_instock_not_backorder) {
        return false;
    }

    return $render_field;
}

注意事项

  • 一定要使用子主题的functions.php,防止主题更新时代码丢失
  • 测试前清除网站缓存,避免缓存导致逻辑不生效
  • 如果tc-row的类名或字段name与代码中不符,需替换为实际值(可通过浏览器开发者工具检查)

内容的提问来源于stack exchange,提问作者Melo Pneu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 23:30:14