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();
	}
}