Automatic Discount on a Customer's First Order
Takes a percentage off the first order of new customers, checked against their account or billing email, to win first-time buyers without coupon codes.
Opens WPIDE on
Code
$wpide_first_order = array(
'percent' => 10, // Percent off the products subtotal.
'label' => 'First order discount', // Line label.
);
add_action( 'woocommerce_cart_calculate_fees', function ( $cart ) use ( $wpide_first_order ) {
if ( ( is_admin() && ! wp_doing_ajax() ) || ! WC()->customer || ! WC()->session ) {
return;
}
$email = is_user_logged_in() ? wp_get_current_user()->user_email : WC()->customer->get_billing_email();
if ( ! is_email( $email ) ) {
return;
}
$cache = (array) WC()->session->get( 'wpide_first_order', array() );
$key = md5( strtolower( $email ) );
if ( ! isset( $cache[ $key ] ) ) {
$previous = wc_get_orders( array(
'billing_email' => $email,
'status' => wc_get_is_paid_statuses(),
'limit' => 1,
'return' => 'ids',
) );
if ( ! $previous && is_user_logged_in() ) {
$previous = wc_get_orders( array( 'customer_id' => get_current_user_id(), 'status' => wc_get_is_paid_statuses(), 'limit' => 1, 'return' => 'ids' ) );
}
$cache[ $key ] = empty( $previous );
WC()->session->set( 'wpide_first_order', $cache );
}
if ( $cache[ $key ] ) {
$cart->add_fee( $wpide_first_order['label'], -$cart->get_subtotal() * $wpide_first_order['percent'] / 100, true );
}
} );
Notes
Guests get the discount once they enter an email address with no previous paid orders, and the check is cached per email for the session.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.