Updates, Tips & Tricks

Updates as Released, Plus My Personal Collection Of WordPress Best Practices

Auto-Apply a Coupon for Specific Products in WooCommerce

03 February

Want a discount to apply automatically when a customer adds certain products to the cart—without forcing them to remember a coupon code? This snippet auto-applies (and removes) a chosen coupon based on product IDs in the cart. It also avoids applying in the admin and supports AJAX cart updates.

Instructions: Replace the coupon_code and product IDs, then add this to your theme’s functions.php (or a custom plugin).

<?php
/**
 * Auto-apply (and auto-remove) a coupon when specific products are in the cart.
 *
 * Add to functions.php or a custom plugin.
 */

add_action(
	'woocommerce_before_calculate_totals',
	function ( $cart ) {

		// Safety checks.
		if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
			return;
		}

		if ( ! $cart || $cart->is_empty() ) {
			return;
		}

		// EDIT THESE:
		$coupon_code = 'auto10'; // Coupon code to apply automatically.
		$trigger_product_ids = array(
			123,
			456,
			789,
		); // Product IDs that trigger the coupon.

		$has_trigger_product = false;

		foreach ( $cart->get_cart() as $cart_item ) {
			$product_id   = isset( $cart_item['product_id'] )
				? (int) $cart_item['product_id']
				: 0;

			$variation_id = isset( $cart_item['variation_id'] )
				? (int) $cart_item['variation_id']
				: 0;

			// Treat variations as their parent product if needed.
			$check_id = $variation_id ? $variation_id : $product_id;

			if (
				in_array( $check_id, $trigger_product_ids, true )
				|| in_array( $product_id, $trigger_product_ids, true )
			) {
				$has_trigger_product = true;
				break;
			}
		}

		// Normalize coupon code.
		$coupon_code = wc_format_coupon_code( $coupon_code );

		// Apply or remove coupon based on cart contents.
		if ( $has_trigger_product ) {
			if ( ! $cart->has_discount( $coupon_code ) ) {
				$cart->add_discount( $coupon_code );
			}
		} else {
			if ( $cart->has_discount( $coupon_code ) ) {
				$cart->remove_coupon( $coupon_code );
			}
		}
	},
	20
);
I hope that was a helpful snippet. Before you go, I recommend checking out all of the heavily discounted WooCommerce extensions I offer on Sozot.com. You can buy any of them at a discount, or get access to all of them for $15/mo via my membership club.
No comments yet.

Leave a Reply