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