在 Woocommerce 存档页面中将 "Sale" 徽章替换为 "Out of Stock"

Replace "Sale" badge by "Out of Stock" in Woocommerce archive pages

我在 woocommerce 商店工作,这里是 the link of the website shop page

本页第一个产品是out of stock。我想在图片上显示 Out of stock 而不是 "Sale!" 徽章。

我该怎么做?

在主题的 functions.php 文件中添加:

add_filter('woocommerce_sale_flash', 'woocommerce_custom_sale_text', 10, 3);
function woocommerce_custom_sale_text($text, $post, $_product)
{
    return '<span class="onsale">out of stock</span>';
}

如果您查看 loop/sale-flash.php 模板,您会发现它有一个用于快速促销的过滤器。您可以将其添加到 functions.php 文件以修改该输出。

add_filter( 'woocommerce_sale_flash', 'sale_flash_stock_status' );
function sale_flash_stock_status( $output_html, $post, $product ){
    if( $product->is_in_stock() ){
        // Leave the sale flash unchanged if it's in stock.
        return $output_html;
    }
    else {
        // Change the html output custom stock status
        $output_html = '<span class="stock-status">' . esc_html__( 'Out of stock', 'woocommerce' ) . '</span>'
        return $output_html;
    }
}

以下代码将在 Woocommerce 档案页面(如商店)上添加一个 "Out of Stock" 缺货产品徽章,在产品销售时替换 "Sale!" 徽章:

// Add badge  "Out of stock" (and replace sale badge)
add_action('woocommerce_before_shop_loop_item_title','custom_before_shop_loop_item_title', 2 ); // Archives pages
function custom_before_shop_loop_item_title(){
    remove_action('woocommerce_before_shop_loop_item_title','woocommerce_show_product_loop_sale_flash', 10 );
    remove_action('woocommerce_after_shop_loop_item_title','woocommerce_show_product_loop_sale_flash', 6 ); // For storefront theme
    add_action('woocommerce_before_shop_loop_item_title','show_product_loop_outofstock_badge', 10 );
}

function show_product_loop_outofstock_badge(){
    global $post, $product;

    if ( $product->get_stock_status() == 'outofstock' ) :
        echo '<span class="onsale outofstock">'. esc_html__('Out of stock', 'woocommerce') .'</span>';
    elseif ( $product->is_on_sale() ) :
        echo '<span class="onsale">'. esc_html__( 'Sale!', 'woocommerce' ) .'</span>';
    endif;
}

You might have to make some hook priority changes, depending on your theme. This code support also storefront theme.

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。