1. Documentation /
  2. Automatically add product to cart on visit

Automatically add product to cart on visit

This is a Developer level doc. If you are unfamiliar with code and resolving potential conflicts, select a WooExpert or Developer for assistance. We are unable to provide support for customizations under our  Support Policy.

Add code to your child theme’s functions.php file or via a plugin that allows custom functions to be added, such as the Code snippets plugin. Avoid adding custom code directly to your parent theme’s functions.php file as this will be wiped entirely when you update the theme.
/**
* 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 );
}
}
}
If you want to automatically add a product to the cart depending on the cart total use the following code: https://gist.github.com/woogists/0928d4b3df4ba423ddb74317a7979527