Getting product stock quantity isn't working

Viewed 41

On single product page I'm trying to get stock quantity or atleast stock status from woocommerce product but it seems not working properly, even if it's simple product (manage stock status is checked) or variable product the button is not showing. And strange thing happens - I've got Yith Product Bundle plugin and even if every item is in stock it shows that button but whatever, that's not main problem.

So here is code I'm using

add_action('woocommerce_before_add_to_cart_button', 'show_wishlist');
 
function show_wishlist() {
    global $product;
    $stockQ=$product->get_stock_quantity();
 
    if ( $stockQ < 1 ) {
        echo "<button>Hello</button>";
    }
}

I've also tried but completely nothing happens.


add_action('woocommerce_before_add_to_cart_button', 'show_wishlist');
 
function show_wishlist() {
    global $product;
 
    if ( ! $product->is_in_stock() ) {
        echo "<button>Hello</button>";
    }
}
1 Answers

First check if the hook is firing properly.

add_action( 'woocommerce_before_add_to_cart_button', 'show_wishlist' );

function show_wishlist(){
    echo '<p>Some custom text before</p>';
} 

If you are able to confirm that the hook is working then use the below code.

    function show_wishlist() {
        global $product;
        // Change In Stock Text
        if ( $product->managing_stock() && $product->is_in_stock() ) {
    //add your code here for Products in Stock
    }
else{
//add your code here for Products out of Stock
}
    }
Related