简体   繁体   English

在 WooCommerce 简单产品的添加到购物车按钮中显示可用性

[英]Display availability in add to cart button for WooCommerce simple products

I have this code which works if I remove the else if part of it, but if doing that, it will show BUY NOW (0 AVAILABLE) when out of stock.我有这个代码,如果我删除 else if 的一部分,它就可以工作,但是如果这样做,它会在缺货时显示立即购买(0 可用)。

I need it to say SOLD OUT when out of stock.缺货时我需要它说 SOLD OUT。 Here's the code I'm using:这是我正在使用的代码:

add_filter( 'woocommerce_product_single_add_to_cart_text', 'atc_with_qty', 10, 2 );
add_filter( 'woocommerce_product_add_to_cart_text', 'atc_with_qty', 10, 2 );
function atc_with_qty( $add_to_cart_button_text, $product ) {

    $stock = $product->get_stock_quantity();

    if ( $product->is_type( 'simple' ) ) {
        $add_to_cart_button_text = __('Buy Now ('.$stock.' Available)', 'woocommerce');
    return $add_to_cart_button_text;

    } else if ( !$product->is_in_stock() && $product->is_type('simple') ) {
        $add_to_cart_button_text = __('SOLD OUT', 'woocommerce');

        return $add_to_cart_button_text;
    }
}

Updated: Your elseif condition, never matches… Try the following instead:更新:您的 elseif 条件,从不匹配……请尝试以下操作:

add_filter( 'woocommerce_product_single_add_to_cart_text', 'add_to_cart_text_availability', 10, 2 );
add_filter( 'woocommerce_product_add_to_cart_text', 'add_to_cart_text_availability', 10, 2 );
function add_to_cart_text_availability( $add_to_cart_text, $product ) {
    if ( $product->is_type( 'simple' ) ) {
        if ( $product->is_in_stock() ) {
            $add_to_cart_text = sprintf( 
                __("Buy Now (%s Available)", "woocommerce"), 
                $product->get_stock_quantity() 
            );
        } else {
            $add_to_cart_text = __('SOLD OUT', 'woocommerce');
        }
    }
    return $add_to_cart_text;
}

Code goes in function.php file of your active child theme (active theme).代码位于活动子主题(活动主题)的 function.php 文件中。 Tested and works.测试和工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM