Skip to content

Instantly share code, notes, and snippets.

@MadCowWeb
Last active April 4, 2024 17:14
Show Gist options
  • Save MadCowWeb/e2d9f86d51f0d54c96a32993786d3ba2 to your computer and use it in GitHub Desktop.
Save MadCowWeb/e2d9f86d51f0d54c96a32993786d3ba2 to your computer and use it in GitHub Desktop.
Add custom content to cart and checkout pages (only if a certain category is in the cart) with an action hook
// CHECK FOR SPECIFIC PRODUCT CATEGORY IN CART
function madcow_custom_category_is_in_the_cart($categories) {
// 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;
}
}
// ADD BANNER TO CART PAGE IF A SPECIFIC CATEGORY IS IN THE CART
add_action('woocommerce_before_cart', 'madcow_above_cart_and_checkout_message');
add_action('woocommerce_after_order_notes', 'madcow_above_cart_and_checkout_message');
function madcow_above_cart_and_checkout_message() {
$categories = array('music');
if (madcow_custom_category_is_in_the_cart($categories)) :
echo '<div class="top-cart-message"><h2>This is our cool message</h2></div>';
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment