Last active
March 22, 2023 15:31
-
-
Save woogists/f24c41bac31f5ec695b98c6b06b3b19f to your computer and use it in GitHub Desktop.
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
/** | |
* 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 ); | |
} | |
} | |
} |
Very useful.
It's not possible to remove the item from the cart with this script as it runs more than once.
Maybe have a counter value stored in a meta field or would there be a better way?
Many thanks.
I want to offer option to remove the product from cart, if the customer doesn't want it. How can I do that?
try this because it only adds the product if the cart is empty:
/**
- Automatically add product to cart on visit
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart()
{
// check if cart contents are empty
if ( WC()->cart->get_cart_contents_count() == 0 )
{
// this code only runs the first time the hook is fired
if ( ! is_admin() )
{
$product_id = 2765; //replace with your own product id
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
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.