-
-
Save wplaunchify/cb89bffbd19f34b286c580947c7eb5ac to your computer and use it in GitHub Desktop.
Code for WooCommerce to check if products in the cart belong to one of the categories we're looking for.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Check if a specific product category is in the cart | |
*/ | |
function wc_ninja_category_is_in_the_cart() { | |
// Add your special category slugs here | |
$categories = array( 'clothing', 'posters' ); | |
// Products currently in the cart | |
$cart_ids = array(); | |
// Categories currently in the cart | |
$cart_categories = array(); | |
// Find each product in the cart and add it to the $cart_ids array | |
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) { | |
$cart_product = $values['data']; | |
$cart_ids[] = $cart_product->id; | |
} | |
// Connect the products in the cart w/ their categories | |
foreach( $cart_ids as $id ) { | |
$products_categories = get_the_terms( $id, 'product_cat' ); | |
// Loop through each product category and add it to our $cart_categories array | |
foreach ( $products_categories as $products_category ) { | |
$cart_categories[] = $products_category->slug; | |
} | |
} | |
// If one of the special categories are in the cart, return true. | |
if ( ! empty( array_intersect( $categories, $cart_categories ) ) ) { | |
return true; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment