Skip to content

Instantly share code, notes, and snippets.

@woogists
Last active March 22, 2023 15:31
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save woogists/f24c41bac31f5ec695b98c6b06b3b19f to your computer and use it in GitHub Desktop.
Save woogists/f24c41bac31f5ec695b98c6b06b3b19f to your computer and use it in GitHub Desktop.
Automatically add product to cart on visit
/**
* Automatically add product to cart on visit
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 64; //replace with your own product id
$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 );
}
}
}
@RavePigeon
Copy link

I want to offer option to remove the product from cart, if the customer doesn't want it. How can I do that?

try this because it only adds the product if the cart is empty:
/**

  • Automatically add product to cart on visit
    */
    add_action( 'template_redirect', 'add_product_to_cart' );
    function add_product_to_cart()
    {
    // check if cart contents are empty
    if ( WC()->cart->get_cart_contents_count() == 0 )
    {
    // this code only runs the first time the hook is fired
    if ( ! is_admin() )
    {
    $product_id = 2765; //replace with your own product id
    WC()->cart->add_to_cart( $product_id );
    }
    }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment