John Davidson

php - woocommerce check how many products of the category wine are inside the cart

0 comments
Message:


I'm trying to make a condition, where a function displays in cart page only, if any product from category wine is present in the cart and how much.



  1. Problem: Currently it does shows me a info of only 1 wine, when i have more different wines in the cart, instead to count all wines.



  2. Problem: i want to drop a message when there are



    • 10, 13, 16 or 19 Bottles in the cart = message 1



    • 11, 14, 17 or 20 Bottles in the cart = message 2






At the moment it works with 1 (e.g. 10) separated number only.


Here is the code:


add_action( 'xoo_wsc_after_footer_btns', 'bbloomer_check_category_in_cart' );
function bbloomer_check_category_in_cart() {
// Set $cat_in_cart to false
$cat_in_cart = false;
$cat_count = 0;
$product_count = 0;
// Loop through all products in the Cart foreach(WC()->cart->get_cart() as $cart_item)
foreach ( WC()->cart->get_cart() as $cart_item ) {

$product = $cart_item['data'];

// If Cart has category "download", set $cat_in_cart to true
if ( has_term( 'wein', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
$product_count += $cart_item['quantity'];

break;
}
}
// Do something if category "download" is in the Cart
if ( $cat_in_cart && $product_count == 10 ) {


// For example, print a notice
wc_print_notice( 'Keine halben Sachen, nur noch 2 Flaschen und der Karton ist voll. Wir belohnen dich mit "due baci"', 'notice' );
}
if ( $cat_in_cart && $product_count == 11 ) {


// For example, print a notice
wc_print_notice( 'Keine halben Sachen, nur noch 1 Flasche und der Karton ist voll. Wir belohnen dich mit "due baci"', 'notice' );
}
}

Any help is appreciated.



My Answer:
>cart->get_cart() as $cart_item_key => $cart_item) {
// Get the product id
$product_id = $cart_item['product_id'];

// Get the product category
$product_categories = get_the_terms($product_id, 'product_cat');

// Check if the product belongs to the wine category
foreach ($product_categories as $category) {
if ($category->name == 'wine') {
$cat_in_cart = true;
$cat_count++;
$product_count += $cart_item['quantity'];
}
}
}

// Display message based on the number of wine bottles in the cart
if ($cat_in_cart) {
if ($product_count == 10 || $product_count == 13 || $product_count == 16 || $product_count == 19) {
echo "Message 1";
} elseif ($product_count == 11 || $product_count == 14 || $product_count == 17 || $product_count == 20) {
echo "Message 2";
}
}
}

Rate this post

3 of 5 based on 7508 votes

Comments




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