Last active
January 18, 2018 10:33
-
-
Save shivapoudel/df81266e7f20fc656f5730fefa7b3aae to your computer and use it in GitHub Desktop.
WooCommerce - Automatically add product to cart on visit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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