Skip to content

Instantly share code, notes, and snippets.

@elliottmangham
Created December 7, 2020 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elliottmangham/95fb4720a946f71e232f6c299b986af4 to your computer and use it in GitHub Desktop.
Save elliottmangham/95fb4720a946f71e232f6c299b986af4 to your computer and use it in GitHub Desktop.
WordPress / WooCommerce / Automatically add product to the cart
/******************************************************************************/
/* 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