WooCommerce Check stock of product ID before adding
<p>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...</p>

<p>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:</p>

<pre><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()-&gt;cart-&gt;get_cart() ) &gt; 0 ) {
        foreach ( WC()-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $values ) {
            $_product = $values['data'];
            if ( $_product-&gt;id == $product_id )
                $found = true;
        }
        // if product not found, add it
        if ( ! $found )
            WC()-&gt;cart-&gt;add_to_cart( $product_id );

        if (sizeof( WC()-&gt;cart-&gt;get_cart() ) == 1 &amp;&amp; $found == true ) {
            $woocommerce-&gt;cart-&gt;empty_cart();
        }
    } 
}
</code></pre>

<p>}</p>