Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 );
}
}
}
@nafilahmed

This comment has been minimized.

Copy link

@nafilahmed nafilahmed commented Mar 27, 2018

how can I add custom info i.e ( custom field value) along with the product

@bdthemes

This comment has been minimized.

Copy link

@bdthemes bdthemes commented Apr 6, 2018

There have an error:

line 14: use if $_product->get_id() instead of $_product->id

@woogists

This comment has been minimized.

Copy link
Owner Author

@woogists woogists commented May 2, 2018

Thanks, @bdthemes! Updated!

@anjanphukan

This comment has been minimized.

Copy link

@anjanphukan anjanphukan commented Sep 19, 2018

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

@freddyrosellorta

This comment has been minimized.

Copy link

@freddyrosellorta freddyrosellorta commented Jun 17, 2020

In my store I would like to automatically add a certain product depending on the category of the product that the user adds. How would it be?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.