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();
}
}
}
}