Woocommerce: Check If Items Are Already in Cart

WooCommerce: Check if items are already in cart

global $woocommerce and $woocommerce->cart is outdated and simply replaced by WC()->cart

Here is a custom function with an argument that accepts a unique integer product ID or an array of product IDs, and that will return the number of matched Ids that are in cart.

The code handle any product type, including variable product and product variations:

function matched_cart_items( $search_products ) {
$count = 0; // Initializing

if ( ! WC()->cart->is_empty() ) {
// Loop though cart items
foreach(WC()->cart->get_cart() as $cart_item ) {
// Handling also variable products and their products variations
$cart_item_ids = array($cart_item['product_id'], $cart_item['variation_id']);

// Handle a simple product Id (int or string) or an array of product Ids
if( ( is_array($search_products) && array_intersect($search_products, cart_item_ids) )
|| ( !is_array($search_products) && in_array($search_products, $cart_item_ids)
$count++; // incrementing items count
}
}
return $count; // returning matched items count
}

This code goes in function.php file of your active child theme (active theme or in any plugin file).

Code is tested and works.


USAGE:

1) For a unique product ID (integer):

$product_id = 102;

// Usage as a condition in an if statement
if( 0 < matched_cart_items($product_id) ){
echo '<p>There is "'. matched_cart_items($product_id) .'"matched items in cart</p><br>';
} else {
echo '<p>NO matched items in cart</p><br>';
}

2) For an array of product IDs:

$product_ids = array(102,107,118);

// Usage as a condition in an if statement
if( 0 < matched_cart_items($product_ids) ){
echo '<p>There is "'. matched_cart_items($product_ids) .'"matched items in cart</p><br>';
} else {
echo '<p>NO matched items in cart</p><br>';
}

3) For an array of product IDs for 3 or more matched cart items for example:

$product_ids = array(102, 107, 118, 124, 137);

// Usage as a condition in an if statement (for 3 matched items or more)
if( 3 <= matched_cart_items($product_ids) ){
echo '<p>There is "'. matched_cart_items($product_ids) .'"matched items in cart</p><br>';
} else {
echo '<p>NO matched items in cart</p><br>';
}

Check if item is already in cart, if yes, then redirect user to checkout without adding product

You can use the following, explanation as comment lines in the code

function my_validation_handler( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Get checkout url
$checkout_url = wc_get_checkout_url();

// Set variable
$in_cart = false;

// Loop
foreach( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['data']->get_id() == $product_id ) {
$in_cart = true;
break;
}
}

// True
if ( $in_cart ) {
wp_safe_redirect( $checkout_url );
exit();
} else {
// Add product to cart
WC()->cart->add_to_cart( $product_id, $quantity );
wp_safe_redirect( $checkout_url );
exit();
}

return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'my_validation_handler', 10, 5 );

Conditional function that check if products are already in cart in Woocommerce 3

Your main function code is outdated.

For Advanced custom fields (ACF):

  • you need to use get_field() (that return the field value) instead of the_field() (that echo the field value).
  • You may need to add a product ID as 2nd argument in get_field('the_slug', $product_id ).

So try:

function is_in_cart( $ids ) {
// Initialise
$found = false;

// Loop Through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// For an array of product IDS
if( is_array($ids) && ( in_array( $cart_item['product_id'], $ids ) || in_array( $cart_item['variation_id'], $ids ) ) ){
$found = true;
break;
}
// For a unique product ID (integer or string value)
elseif( ! is_array($ids) && ( $ids == $cart_item['product_id'] || $ids == $cart_item['variation_id'] ) ){
$found = true;
break;
}
}

return $found;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

The custom conditional function is_in_cart( $ids ) accept a string (a unique product Id) or an array of product Ids.


Your revisited usage (ACF get_field may need a post ID (product ID)):

if ( is_in_cart( "69286" ) ) {
echo '<p>' . get_field ( 'cart_field' ) . '</p>'; // or get_field ( 'cart_field', "69286" )
}
if ( is_in_cart( "69287" ) ) {
echo '<p>' . get_field ( 'cart_field-1' ) . '</p>'; // or get_field ( 'cart_field', "69287" )
}

Woocommerce: function to check if the cart contains any product

This could help:

if(WC()->cart && !WC()->cart->is_empty()){
// the cart has products
}

WooCommerce if condition (if product is in cart do something)

In the end I used external function:

function woo_is_in_cart($product_id) {
global $woocommerce;
foreach($woocommerce->cart->get_cart() as $key => $val ) {
$_product = $val['data'];
if($product_id == $_product->get_id() ) {
return true;
}
}
return false;
}

Then I check if the product is in cart using this:

if(woo_is_in_cart(5555) !=1) {
/* where 5555 is product ID */

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

The code below uses the custom function has_bought(). It auto add to cart a different product for new customers and confirmed customers:

add_action( 'template_redirect', 'add_product_to_cart_conditionally' );
function add_product_to_cart_conditionally() {
if ( is_admin() ) return; // Exit

// Below define the product Id to be added:
$product_A = 37; // <== For new customers that have not purchased a product before (and guests)
$product_B = 53; // <== For confirmed customers that have purchased a product before

$product_id = has_bought() ? $product_B : $product_A;

// If cart is empty
if( WC()->cart->is_empty() ) {
WC()->cart->add_to_cart( $product_id ); // Add the product
}
// If cart is not empty
else {
// Loop through cart items (check cart items)
foreach ( WC()->cart->get_cart() as $item ) {
// Check if the product is already in cart
if ( $item['product_id'] == $product_id ) {
return; // Exit if the product is in cart
}
}
// The product is not in cart: We add it
WC()->cart->add_to_cart( $product_id );
}
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related: Checking if customer has already bought something in WooCommerce

Check for Product Category in cart items with WooCommerce

The correct way for cart items to be used with product categories is:

add_action('woocommerce_before_cart', 'action_before_cart');
function action_before_cart() {
$categories = array('ilutulestik-2');
$has_category = false;

// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Check for product categories
if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$has_category = true;
break;
}
}

// Testing output (display a notice)
if ( $has_category ) {
wc_print_notice( sprintf( 'Product category "%s" is in cart!', reset($categories)), 'notice' );
}
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


If you need to check also for parent terms with product categories, you will use instead:

// Custom conditional function that handle parent product categories too
function has_product_categories( $categories, $product_id = 0 ) {
$parent_term_ids = $categories_ids = array(); // Initializing
$taxonomy = 'product_cat';
$product_id = $product_id == 0 ? get_the_id() : $product_id;

if( is_string( $categories ) ) {
$categories = (array) $categories; // Convert string to array
}

// Convert categories term names and slugs to categories term ids
foreach ( $categories as $category ){
$result = (array) term_exists( $category, $taxonomy );
if ( ! empty( $result ) ) {
$categories_ids[] = reset($result);
}
}

// Loop through the current product category terms to get only parent main category term
foreach( get_the_terms( $product_id, $taxonomy ) as $term ){
if( $term->parent > 0 ){
$parent_term_ids[] = $term->parent; // Set the parent product category
$parent_term_ids[] = $term->term_id; // (and the child)
} else {
$parent_term_ids[] = $term->term_id; // It is the Main category term and we set it.
}
}
return array_intersect( $categories_ids, array_unique($parent_term_ids) ) ? true : false;
}

add_action('woocommerce_before_cart', 'action_before_cart');
function action_before_cart() {
$categories = array('ilutulestik-2');
$has_category = false;

// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Check for product categories
if ( has_product_categories( $cart_item['product_id'], $categories ) ) {
$has_category = true;
break;
}
}

// Testing output (display a notice)
if ( $has_category ) {
wc_print_notice( sprintf( 'Product category "%s" is in cart!', reset($categories)), 'notice' );
}
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Checking cart items for a product category in Woocommerce

To check product categories in cart items using WordPress has_term() conditional function, you need to use $cart_item['product_id'] instead to handle checking product categories in product variations too.

This way it check in the parent variable product for the product category as product variation type doesn't handle any custom taxonomy. So now it will work for all cases.

So your revisited code will be:

add_action('woocommerce_before_cart', 'check_product_category_in_cart');
function check_product_category_in_cart() {
// HERE set your product categories in the array (can be IDs, slugs or names)
$categories = array('downloads');
$found = false; // Initializing

// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// If product categories is found
if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$found = true; // Set to true
break; // Stop the loop
}
}

// If any defined product category is found, we display a notice
if ( $found ) {
wc_print_notice( __('Product Category "Downloads" is in Cart items!'), 'notice' );
}
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Check if this Variation ID exists in cart, then add another item to cart

Slight Modification in foreach loop to get & compare variations might resolve the issue

foreach( WC()->cart->get_cart() as $cart_item_key => $values ) { 

$variation_ids = array(11264,11265);

//check if variation exist in cart & if found add product in cart with ID 111

if( in_array( $values['variation_id'], $variation_ids ) ) {

WC()->cart->add_to_cart(111);
}
else {

//Do something

}
}


Related Topics



Leave a reply



Submit