I'm trying to make a condition, where a function displays on WooCommerce checkout page only, if any product from category ilutulestik
is present in the shopping cart.
Currently, however, it does not seem to be able to obtain cart info. I assume that because, if I use if ( $cat_in_cart )
condition on a code, the function I use it on, does not display, even if I have a product from ilutulestik
category present in the shopping cart.
I've tried many different methods to obtain cart info, but none have seemed to work. I'll include 2 ways of how I tried below:
Try 1
add_action('woocommerce_before_cart', 'kontrollime_ilutulestiku_olemasolu');
function kontrollime_ilutulestiku_olemasolu()
{
global $woocommerce;
$cat_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values )
{
$item = $values['data'];
$item_id = $item->id;
if ( has_term( 'ilutulestik-2', 'product_cat', $item_id ) )
{
$cat_in_cart = true;
break;
}
}
}
Try 2
add_action('woocommerce_before_cart', 'kontrollime_ilutulestiku_olemasolu');
function kontrollime_ilutulestiku_olemasolu($package)
{
global $woocommerce;
$cat_in_cart = false;
foreach ($package['contents'] as $product)
{
// get product categories
$product_cats = wp_get_post_terms(
$product['product_id'], 'product_cat', array('fields' => 'names') );
// if it has category_name unset flat rate
if( in_array('ilutulestik-2', $product_cats) )
{
$cat_in_cart = true;
break;
}
}
}
I expect this piece of code to check if there is a product in cart that belongs to category Ilutulestik
(or slug ilutulestik-2
) and if it does, change $cat_in_cart
value to true
, so later I could activate any code with if ( $cat_in_cart )
.