WooCommerce Check stock of product ID before adding

11,254

Solution 1

You can use the WC_Product conditional method is_in_stock() directly in your if statement.

As $product is already a product object, we don't need anything else to make it work with WC_product methods.

Also instead of using sizeof( WC()->cart->get_cart() ) > 0 you can replace by the WC_cart method is_empty() this way ! WC()->cart->is_empty().

Then you can also replace sizeof( WC()->cart->get_cart() ) == 1 using WC_cart get_cart_contents_count() method this way WC()->cart->get_cart_contents_count() == 1.

You don't need anymore the global woocommerce; declaration if you use WC()->cart instead of $woocommerce->cart with all WC_Cart methods

Last thing:
May be is better to remove the concerned cart item, instead emptying the cart. So we will use remove_cart_item() method instead.
If is not convenient you can use empty_cart() method as in your original code…

So your code is going to be:

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $targeted_product_id = 21576;
        $found = false;

        //check if product already in cart

        if ( ! WC()->cart->is_empty() ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                $product = $cart_item['data'];
                if ( $product->id == $targeted_product_id ) {
                    $found = true;
                    break; // We can break the loop
                }
            }
            // Update HERE (we generate a new product object $_product)
            $_product = wc_get_product( $targeted_product_id );
            // If product is not in the cart items AND IT IS IN STOCK
            if ( !$found && $_product->is_in_stock() ) {
                WC()->cart->add_to_cart( $targeted_product_id );
            } 
            elseif ( $found && WC()->cart->get_cart_contents_count() == 1 ) {
                // Removing only this cart item
                WC()->cart->remove_cart_item( $cart_item_key );
                // WC()->cart->empty_cart();
            }
        }
    } 
}

This code is tested and works.

Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.

Solution 2

This statement will return true if the stock quantity of the product is greater than 0.

if( $product->get_stock_quantity() > 0 ) {
    WC()->cart->add_to_cart( $product->id );
}

I see you're setting the product ID yourself. If you need to get the product by the product it, in order to runt he code above, this may help you.

$product = wc_get_product( $product_id );
Share:
11,254
user2115227
Author by

user2115227

Freelance Designer + Developer. Latest Project: https://www.geeks-hut.com

Updated on June 04, 2022

Comments

  • user2115227
    user2115227 almost 2 years

    I have some custom code in my WooCommerce site that adds a product to the users cart. I already have it check the cart contents to make sure there is another product in the cart first, but I also want it to check that the product that is being added is in stock also...

    I can't work out the best way to do this. Would really appreciate if you can let me know what to add to the function to make it check the stock of "product_id" and if the stock is > 0. Here's my code:

    add_action( 'template_redirect', 'add_product_to_cart' );
    function add_product_to_cart() {
        if ( ! is_admin() ) {
            $product_id = 21576;
            $found = false;
            global $woocommerce;
    
            //check if product already in cart
    
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->id == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
    
            if (sizeof( WC()->cart->get_cart() ) == 1 && $found == true ) {
                $woocommerce->cart->empty_cart();
            }
        } 
    }
    

    }

  • user2115227
    user2115227 over 7 years
    Thanks for the comment. I tried the above code, but get the following error: Fatal error: Call to undefined method WP_Post::get_stock_quantity()
  • Ryan Kozak
    Ryan Kozak over 7 years
    get_stock_quantity() is actually defined in the WC_Product Class. I've edited my answer, see the last line and if that perhaps functions for you.
  • user2115227
    user2115227 over 7 years
    This still throws up an error...Fatal error: Call to a member function is_in_stock() on a non-object in /nas/content/staging/tulaforlife/wp-content/plugins/tula/ind‌​ex.php on line 135
  • user2115227
    user2115227 over 7 years
    This has stopped the error from showing, but it now doesn't add the product at all. :(
  • user2115227
    user2115227 over 7 years
    Thanks for keeping at this. I noticed the variable is incorrect in WC()->cart->add_to_cart( $product_id ); (should be $targeted_product_id). If i changed this, with your new code, it now works - however it does still attempt to add the product even if the stock level is 0, and shows a message on the cart saying that it cant add the product because it's out of stock :(
  • user2115227
    user2115227 over 7 years
    Thanks :) It still doesn't work though. It adds the product if it's in stock, if it's not in stock, it still tries to add the product, and then shows a message saying the product is out of stock so can't add it. This is what I'm trying to avoid - so if it's out of stock, it just doesn't try to add it. :/
  • LoicTheAztec
    LoicTheAztec over 7 years
    @user2115227 this is very strange as $product->is_in_stock() should avoid this … Updated the code… but this is still very strange
  • user2115227
    user2115227 over 7 years
    what did you change? Whatever it was has fixed it, it now works as I wanted it - thanks! :)