Skip to content

Instantly share code, notes, and snippets.

@jkohlbach
Created November 6, 2013 05:38
Show Gist options
  • Save jkohlbach/7331462 to your computer and use it in GitHub Desktop.
Save jkohlbach/7331462 to your computer and use it in GitHub Desktop.
Automatically apply a coupon to a user's first order in WooCommerce
add_action('woocommerce_before_cart', 'firstTimeShopper');
add_action('woocommerce_before_checkout_form', 'firstTimeShopper');
function firstTimeShopper() {
global $woocommerce;
$coupon_code = 'firstimeshopper'; // Change this to whatever your coupon code is
if (is_user_logged_in()) {
$current_user = wp_get_current_user();
if (!$current_user)
return;
$hasOrderedBefore = get_user_meta($current_user->ID, 'paying_customer', true);
if (!$hasOrderedBefore) {
// If coupon has been already been added remove it.
if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code)))
if (!$woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code)))
$woocommerce->show_messages();
// Add coupon
if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) {
$woocommerce->show_messages();
} else {
$woocommerce->clear_messages();
// Change this message to whatever you like
$woocommerce->add_message("Hi there! <b>Because this is your first order we've applied a 10% discount.</b> No hidden catches, we just want to say thanks!");
$woocommerce->show_messages();
}
// Recalculate totals.
$woocommerce->cart->calculate_totals();
} else {
// Is not user's first time shopping
if ($woocommerce->cart->has_discount(sanitize_text_field($coupon_code))) {
if ($woocommerce->cart->remove_coupons(sanitize_text_field($coupon_code)))
$woocommerce->show_messages();
//Recalculate totals.
$woocommerce->cart->calculate_totals();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment