Coupon

Apply a coupon depending on cart weight 

add_action( 'woocommerce_before_cart', 'snipjar_apply_coupon_cart_weight' );

function snipjar_apply_coupon_cart_weight() {
	$coupon_code = 'snipdeal';
	// if cart content weight is more than 15kg
	if( 15 < WC()->cart->get_cart_contents_weight() ) {
		if( ! WC()->cart->has_discount( $coupon_code ) ) {
			WC()->cart->apply_coupon( $coupon_code );
		}
	} else {
		WC()->cart->remove_coupon( $coupon_code );
		WC()->cart->calculate_totals();
	}
}

Apply a coupon depending on cart subtotal 

add_action( 'woocommerce_before_cart', 'snipjar_apply_coupon_cart_subtotal' );

function snipjar_apply_coupon_cart_subtotal() {
	$coupon_code = 'snipdeal';
	// if cart subtotal is more than 10,000
	if( 10000 < WC()->cart->get_subtotal() ) {
		if( ! WC()->cart->has_discount( $coupon_code ) ) {
			WC()->cart->apply_coupon( $coupon_code );
		}
	} else {
		WC()->cart->remove_coupon( $coupon_code );
		WC()->cart->calculate_totals();
	}
}

Apply a coupon depending on a number of products in the cart

add_action( 'woocommerce_before_cart', 'shipjar_apply_coupon_number_of_products' );

function shipjar_apply_coupon_number_of_products() {
	$coupon_code = 'snipdeal';
	// if there are more than 5 different products in the cart
	if( 5 < count( WC()->cart->get_cart() ) ) {
		if( ! WC()->cart->has_discount( $coupon_code ) ) {
			WC()->cart->apply_coupon( $coupon_code );
		}
	} else {
		WC()->cart->remove_coupon( $coupon_code );
		WC()->cart->calculate_totals();
	}
}

Apply a coupon if there is a specific product in cart 

When a customer purchases a specific product you may want to provide a specific discount to all the products in the cart automatically.

add_action( 'woocommerce_before_cart', 'snipjar_apply_coupon_specific_product' );

function snipjar_apply_coupon_specific_product() {
	$coupon_code = 'snipdeal';
	$product_id = 678;
	// if product in the cart
	if( in_array( $product_id, array_column( WC()->cart->get_cart(), 'product_id' ) ) ) {
		if( ! WC()->cart->has_discount( $coupon_code ) ) {
			WC()->cart->apply_coupon( $coupon_code );
		}
	} else { // if product removed from cart we remove the coupon
		WC()->cart->remove_coupon( $coupon_code );
		WC()->cart->calculate_totals();
	}
}