John Davidson

php - Check if customer has purchased something and add product to cart in WooCommerce

0 comments
Message:


The code below auto add a product to cart in WooCommerce:


add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 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 ( $_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 );
}
}
}

The answer Checking if customer has already bought something in WooCommerce allows to check if user has already make a purchase or not with a custom conditional function has_bought().


So what I would like is to check if the customer has ordered before and:



  • If it's their first order, force product A into the cart OR

  • If they've already made one or more purchases, force product B into
    the cart


But I didn't find the way to use it in my code.


Any help will be appreciated.



My Answer:
>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;_ break;_ }_ }_ // if product not found, add it to cart_ if ( ! $found ) {_ WC()->cart->add_to_cart( $product_id );_ }_ } else {_ WC()->cart->add_to_cart( $product_id );_ }_ }_}

Rate this post

4 of 5 based on 9510 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us