Skip to content

Instantly share code, notes, and snippets.

@shivapoudel
Last active January 18, 2018 10:33
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 shivapoudel/df81266e7f20fc656f5730fefa7b3aae to your computer and use it in GitHub Desktop.
Save shivapoudel/df81266e7f20fc656f5730fefa7b3aae to your computer and use it in GitHub Desktop.
WooCommerce - Automatically add product to cart on visit
<?php // Do not include this if already open!
/**
* Code goes in theme functions.php.
*/
if ( class_exists( 'WooCommerce' ) ) {
add_action( 'template_redirect', 'wc_auto_add_product_to_cart' );
}
/**
* Add product item to cart on site visit.
*/
function wc_auto_add_product_to_cart() {
$product = get_page_by_title( 'Sunglasses', OBJECT, 'product' );
if ( is_object( $product ) && $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->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 );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment