Halloween Sale 15% off Ends in See the plans
PHP

Coupon Codes for First Orders Only

Limits chosen coupon codes, such as a welcome discount, to customers who have never placed a paid order, checked by account and billing email.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_welcome_coupons = array( 'welcome10', 'firstorder' ); // Coupon codes.

add_filter( 'woocommerce_coupon_is_valid', function ( $valid, $coupon ) use ( $wpide_welcome_coupons ) {
    if ( ! in_array( wc_format_coupon_code( $coupon->get_code() ), array_map( 'wc_format_coupon_code', $wpide_welcome_coupons ), true ) ) {
        return $valid;
    }

    $email = is_user_logged_in() ? wp_get_current_user()->user_email : ( WC()->customer ? WC()->customer->get_billing_email() : '' );
    $query = array( 'status' => wc_get_is_paid_statuses(), 'limit' => 1, 'return' => 'ids' );
    $found = array();

    if ( is_user_logged_in() ) {
        $found = wc_get_orders( $query + array( 'customer_id' => get_current_user_id() ) );
    }

    if ( ! $found && is_email( $email ) ) {
        $found = wc_get_orders( $query + array( 'billing_email' => $email ) );
    }

    if ( $found ) {
        throw new Exception( esc_html( 'This welcome coupon is only valid on your first order.' ), 100 );
    }

    return $valid;
}, 10, 2 );

Notes

Guests are checked by the billing email entered at checkout, so the code may be accepted in the cart and refused at checkout.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.