Search code examples
phpwordpresswoocommerceproductproduct-quantity

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.

I need it to say SOLD OUT when out of stock. 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;
    }
}

Solution

  • Updated: Your elseif condition, never matches… Try the following instead:

    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). Tested and works.