求助:修改WooCommerce库存剩余2件及以下时的提示文本
修改WooCommerce低库存提示文本的方法
- 直接通过WooCommerce的过滤器钩子修改,将以下代码添加到主题的
functions.php文件(推荐使用子主题,避免主题更新丢失代码)或自定义插件中:
add_filter( 'woocommerce_get_availability_text', 'custom_low_stock_notice_text', 10, 2 ); function custom_low_stock_notice_text( $text, $product ) { // 匹配库存≤2且商品在售的情况 if ( $product->get_stock_quantity() <= 2 && $product->is_in_stock() ) { $text = sprintf( 'Hurry! Only %d left in stock', $product->get_stock_quantity() ); } return $text; }
- 代码作用:拦截默认的库存提示文本,当商品库存数量为2件及以下时,自动在原有文本前添加"Hurry!"前缀,同时保留动态的库存数字。
- 验证方式:添加代码后,刷新商品页面,查看低库存商品的提示文本是否已更新。
内容的提问来源于stack exchange,提问作者Daphne V.
相关产品推荐
相关产品推荐

