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

WooCommerce隐藏缺货价格时移除可变产品空price span标签

WooCommerce 缺货产品隐藏价格并移除空标签方案

现有实现基础

WooCommerce默认行为:无库存但已设置价格的产品,前端会正常展示价格。
现有代码通过挂载woocommerce_get_price_html过滤器实现了缺货产品价格内容隐藏,代码如下:

function hide_price_if_out_stock_frontend( $price, $product ) {
    if ( ! $product->is_in_stock() ) {
        $price = apply_filters( 'woocommerce_empty_price_html', '', $product );
    }
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'hide_price_if_out_stock_frontend', 9999, 2 );

现存问题

  • 简单产品:上述代码仅清空了<p class="price">标签内的价格内容,已通过覆写主题内WooCommerce模板single-product/price.php,完全移除了残留的空<p class="price"></p>标签,覆写后的模板代码如下:
<?php
/**
 * Single Product Price
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/single-product/price.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 3.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

global $product;

?>
<?php if ( ! $product->is_type( 'variable' ) ) { ?>
<p class="<?php echo esc_attr( apply_filters( 'woocommerce_product_price_class', 'price' ) ); ?>"><?php echo $product->get_price_html(); ?></p>
<?php } ?>
  • 可变产品:上述代码仅清空了<span class="price">标签内的价格内容,页面仍残留空的<span class="price"></span>标签。直接修改WooCommerce核心文件/plugins/woocommerce/includes/class-wc-product-variable.php存在兼容性风险,需通过官方提供的钩子实现无侵入修改。

最终实现代码

1. 修正全局价格隐藏逻辑

替换原有hide_price_if_out_stock_frontend函数,可变产品自带的<span class="price">包装器会在过滤器触发时一并传入,直接返回空值即可完全移除标签,不会残留空结构:

function hide_price_if_out_stock_frontend( $price, $product ) {
    if ( ! $product->is_in_stock() ) {
        // 直接返回空,包含价格标签在内的整个价格结构会被清空
        return '';
    }
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'hide_price_if_out_stock_frontend', 9999, 2 );

2. 处理变体选择时的动态价格

追加woocommerce_available_variation钩子处理,当选中的单个变体缺货时,直接清空返回的价格HTML字段,避免动态加载变体数据时出现空标签:

add_filter( 'woocommerce_available_variation', 'remove_outofstock_variation_price', 9999, 3 );
function remove_outofstock_variation_price( $variation_data, $parent_product, $variation ) {
    if ( ! $variation->is_in_stock() ) {
        $variation_data['price_html'] = '';
    }
    return $variation_data;
}

补充说明

以上代码无需修改任何WooCommerce核心文件,全部通过官方提供的过滤器实现,兼容后续WooCommerce版本更新。如果需要在隐藏价格的位置展示「缺货」类自定义提示,直接将返回空字符串的位置替换为自定义内容即可。

内容的提问来源于stack exchange,提问作者social.reza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 12:54:16