Created
November 17, 2017 12:54
-
-
Save ihorduchenko/6c5a43eef3d30d5a03af113de1ece2ee to your computer and use it in GitHub Desktop.
Automatically add products to cart when visit page
This file contains hidden or 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
add_action( 'template_redirect', 'add_product_to_cart' ); | |
function add_product_to_cart() { | |
if ( ! is_admin() ) { | |
$articles = array(64); | |
$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 (($key = array_search($_product->id, $articles)) !== false) | |
unset($articles[$key]); | |
} | |
// if product not found, add it | |
if ( count($articles) > 0 ) { | |
foreach ($articles as $article) { | |
WC()->cart->add_to_cart($article); | |
} | |
} | |
} else { | |
// if no products in cart, add it | |
foreach ($articles as $article) { | |
WC()->cart->add_to_cart( $article ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment