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();
}
}
}
}
Also instead of using
sizeof( WC()->cart->get_cart() ) > 0you can replace by the WC_cart methodis_empty()this way! WC()->cart->is_empty().Then you can also replace
sizeof( WC()->cart->get_cart() ) == 1using WC_cartget_cart_contents_count()method this wayWC()->cart->get_cart_contents_count() == 1.You don't need anymore the
global woocommerce;declaration if you useWC()->cartinstead of$woocommerce->cartwith all WC_Cart methodsSo your code is going to be:
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.