Created
December 7, 2020 08:49
-
-
Save elliottmangham/95fb4720a946f71e232f6c299b986af4 to your computer and use it in GitHub Desktop.
WordPress / WooCommerce / Automatically add product to the cart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************************************************************************/ | |
/* Automatically adding the product to the cart. | |
/* https://www.tychesoftwares.com/how-to-automatically-add-a-product-to-your-woocommerce-cart-in-3-different-scenarios/ | |
/******************************************************************************/ | |
function auto_add_product_to_cart() { | |
if ( ! is_admin() ) { | |
$product_id = 2623; // Product ID which will get added to cart. Should be dynamic. | |
$found = false; | |
//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->get_id() == $product_id ) $found = true; | |
} | |
// If product not found, add it | |
if ( ! $found ) WC()->cart->add_to_cart( $product_id ); | |
} else { | |
// If no products in cart, add it | |
WC()->cart->add_to_cart( $product_id ); | |
} | |
} | |
} | |
//add_action( 'init', 'auto_add_product_to_cart' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment