We often add coupons to our online store based on special occasions. These coupons are usually only valid for specific categories of products. Therefore, we want to show the available coupons to customers based on the products in their carts. This way, customers can take advantage of any discounts available to them.
We need to add the Advanced Custom Fields free plugin for this to function. ACF plugin will be used to add a related field in taxonomy term pages.
After installing the ACF plugin, add a new Field Group with a Relationship type field, as shown in the image below
Set the location to Taxonomy and value as Category (product_cat) as shown in the image below.
Now go to the product category listing page under Products and edit any category term.
Add a coupon to the category and update it.
PHP Snippet: To show the discount coupon applicable for certain products on the cart page –
function bcloud_display_coupons_cart(){
global $wp;
$current_slug = add_query_arg( array(), $wp->request );
if ($current_slug == 'cart-testing' || $current_slug == 'cart'){
$coupons = array();
$coupons_codes = array(); // to be used to avoid adding same coupon code multiple times
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$category_types = wp_get_post_terms( $cart_item['product_id'], 'product_cat');
foreach ( $category_types as $category_type ) {
$related_coupons = get_term_meta($category_type->term_id, 'related_coupons', true);
if ($related_coupons){
foreach($related_coupons as $related_coupon){
$coupon_obj = get_post($related_coupon);
if ($coupon_obj && ! in_array($coupon_obj->post_title, $coupons_codes)){
array_push($coupons_codes, $coupon_obj->post_title);
array_push($coupons, $coupon_obj);
}
}
}
}
}
if (empty($coupons)){
return;
}
echo '<br><h4>Available Coupons</h4>';
foreach($coupons as $coupon){
echo "<span>Code: <strong>{$coupon->post_title}</strong></span><span> Description: {$coupon->post_excerpt}</span><br><br>";
}
}
}
add_action('woocommerce_after_cart_table', 'bcloud_display_coupons_cart');
//add_action('woocommerce_cart_coupon', 'bcloud_display_coupons_cart');
After adding the above code, available coupons will show on the cart page based on products in the cart.
We have hooked our code to woocommerce_after_cart_table action. You can hook it with the woocommerce_cart_coupon action to show available coupons above the Update Cart button. Or you can choose the action hook based on this visual guide of cart page hooks.