Apply coupon if user bought a specific product

Recently I had to do discount in WooCommerce if a user is bought a specific product – in this case “Membership” product.
The fallowing code will check if a user is bought a product with given id, and if so it will apply specified coupon code.

Just place the fallowing at the end of your functions.php in your theme:

// Apply coupon programmatically if specific product is bought

add_action( 'woocommerce_before_cart', 'auto_add_coupon' );

function auto_add_coupon() {
    global $woocommerce;

    $coupon_code = 'membership-cc';

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    foreach ($woocommerce->cart->cart_contents as $key => $values ) {

    $target_product = array(5183);

		$current_user = wp_get_current_user();
		if (woocommerce_customer_bought_product($current_user->user_email, $current_user->ID, $target_product)){

        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();
    }
    }

}