• Hi
    I am trying to make two PHP variables. One must be assigned the value “true” if there is in the cart ONLY one or more products with the product categories which have the IDs ’21’, ’19’, ’16’, ’20’, ’22’.

    The second variable must be assigned the value “true” if there is one or more items in the cart with the product categories that have the IDs ’21’, ’19’, ’16’, ’20’, ’22’ AND one or more products from other product categories.

    I’ve tried the code below, but it does not work… any suggestions?

    // Loop through all products in the Cart
    	foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    
    		$var1 = false;
    		$var2 = false;
    		$excluded_cats = array( '21', '19', '16', '20', '22' );
    
    		if ( has_term( array('21', '19', '16', '20', '22'), 'product_cat', $cart_item['product_id'] ) && has_term( $cart_item['product_id'], 'product_cat', $excluded_cats ) ) {
    			$var1 = true;
    			break;
    		} else if (has_term( array('21', '19', '16', '20', '22'), 'product_cat', $cart_item['product_id'] ) && !has_term( $cart_item['product_id'], 'product_cat', $excluded_cats )) {
    			$var2 = true;
    			break;
    		}
    	}

    What I need is just a variable that contains all product categories except the categories with the ids ’21’, ’19’, ’16’, ’20’, ’22’.

    • This topic was modified 3 years, 7 months ago by oscarsk.
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Maybe it’s wrong to do so, but I’m going to disregard much of your topic and focus on only the last sentence. If you can’t get what you need from just that, I’ll take a closer look at the rest.

    First, initialize an empty, overall array that’ll eventually contain all the desired category IDs without any undesired ones. You correctly need to loop through all product posts in the cart. From there, here’s what I’d do. Use wp_get_post_terms() to get just the assigned product_category IDs. You can use the “fields” argument to get just the IDs. Use array_merge() to add the IDs to the overall array. There will likely be duplicates. Don’t worry about that for now. Continue for all the products in the cart.

    After the loop completes, use array_unique() to get rid of all the duplicate IDs. Then use array_diff() to get rid of the undesired IDs. You now have all the IDs you seek. If you need complete term objects, use the ID array as source for array_map() in conjunction with “get_term” as callback. Or loop through the IDs to build an array of objects using get_term(), it’s essentially the same process either way.

Viewing 1 replies (of 1 total)
  • The topic ‘has_term() all product categories but exclude some’ is closed to new replies.