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?

@steve-s-eightball-media

This comment has been minimized.

Copy link

@steve-s-eightball-media steve-s-eightball-media commented Jan 24, 2021

Thank you for the script.

I try it on my website, but it triggers an error to the website. Following is the error message.

An error of type E_ERROR was caused in line 13 of the file /nas/content/live/acewasteprod/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code. Error message: Uncaught Error: Call to a member function get_cart() on null in /nas/content/live/acewasteprod/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code:13

Does anyone know how to resolve this issue?

Thank you in advance.

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