First order discount for guest customers checking Woocommerce orders billing emailDouble posting from wordpress to tumblr using curl/phpWoocommerce Check if Guest CustomerOrder Confirmation/Completion email not sent for GUESTs in WoocommerceCustomize WooCommerce order emailWooCommerce custom coupon discountWoocommerce custom discountAdd Tip input by customer to WooCommerce checkout pageGet the Order billing city in WooCommerce email-customer-details.php email templateWoocommerce Order By Billing NameChange the sender email to the customer billing email in Woocommerce

Group by consecutive index numbers

In what language did Túrin converse with Mím?

Scaling arrows.meta with tranform shape

Are spot colors limited and why CMYK mix is not treated same as spot color mix?

Why is 3/4 a simple meter while 6/8 is a compound meter?

Is there an in-universe explanation given to the senior Imperial Navy Officers as to why Darth Vader serves Emperor Palpatine?

Under GDPR, can I give permission once to allow everyone to store and process my data?

'Horseshoes' for Deer?

Why did Starhopper's exhaust plume become brighter just before landing?

How to handle inventory and story of a player leaving

Is the Amazon rainforest the "world's lungs"?

What caused the end of cybernetic implants?

Create a list of snaking numbers under 50,000

RAID0 instead of RAID1 or 5, is this crazy?

What should be done with the carbon when using magic to get oxygen from carbon dioxide?

Does Dovescape counter Enchantment Creatures?

Group riding etiquette

Do manacles provide any sort of in-game mechanical effect or condition?

How can I reply to coworkers who accuse me of automating people out of work?

I feel cheated by my new employer, does this sound right?

Printing a list as "a, b, c." using Python

Inspiration for failed idea?

Answer with an image of my favorite musician

Why do IR remotes influence AM radios?



First order discount for guest customers checking Woocommerce orders billing email


Double posting from wordpress to tumblr using curl/phpWoocommerce Check if Guest CustomerOrder Confirmation/Completion email not sent for GUESTs in WoocommerceCustomize WooCommerce order emailWooCommerce custom coupon discountWoocommerce custom discountAdd Tip input by customer to WooCommerce checkout pageGet the Order billing city in WooCommerce email-customer-details.php email templateWoocommerce Order By Billing NameChange the sender email to the customer billing email in Woocommerce






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















By checking the GUEST customer's email address against processing and completed orders, I want to give the GUEST a "first order discount" if the email has no orders. It would be nice if this could happen as the guest types in their email.



I think I've managed to make the discount code and now I am asking for help on merging these two codes, making it all work.



Here's the discount code:



add_action( 'woocommerce_cart_calculate_fees', 'first_time_order_discount', 10, 1 );
function first_time_order_discount( $wc_cart )

if ( is_admin() && ! defined('DOING_AJAX') ) return;

// discount percentage, change this into whatever you like
// currently set to 5%
$percent = 5;

// calculate first order discount based on the percentage above
$first_order_discount = $wc_cart->cart_contents_total * $percent / 100;
$wc_cart->add_fee( __( 'First Order Discount', 'woocommerce')." ($percent%)", -$first_order_discount );



And here's the control code:



function has_bought( $customer_email )
$orders = get_posts( array(
'numberposts' => -1,
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed'),
) );

$email_array = array();

foreach($orders as $order)
$order_obj = wc_get_order($order->ID);
$order_obj_data = $order_obj->get_data();
array_push($email_array, $order_obj_data['billing']['email']);

if (in_array($customer_email, $email_array))
return true;
else
return false;




Not sure how to merge these two into one.










share|improve this question


























  • @helgatheviking you would not be able to help with this?

    – user11256696
    Mar 28 at 10:57











  • Just for info: Re-enable deleted answer and updated… check it please.

    – LoicTheAztec
    Mar 29 at 0:20

















2















By checking the GUEST customer's email address against processing and completed orders, I want to give the GUEST a "first order discount" if the email has no orders. It would be nice if this could happen as the guest types in their email.



I think I've managed to make the discount code and now I am asking for help on merging these two codes, making it all work.



Here's the discount code:



add_action( 'woocommerce_cart_calculate_fees', 'first_time_order_discount', 10, 1 );
function first_time_order_discount( $wc_cart )

if ( is_admin() && ! defined('DOING_AJAX') ) return;

// discount percentage, change this into whatever you like
// currently set to 5%
$percent = 5;

// calculate first order discount based on the percentage above
$first_order_discount = $wc_cart->cart_contents_total * $percent / 100;
$wc_cart->add_fee( __( 'First Order Discount', 'woocommerce')." ($percent%)", -$first_order_discount );



And here's the control code:



function has_bought( $customer_email )
$orders = get_posts( array(
'numberposts' => -1,
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed'),
) );

$email_array = array();

foreach($orders as $order)
$order_obj = wc_get_order($order->ID);
$order_obj_data = $order_obj->get_data();
array_push($email_array, $order_obj_data['billing']['email']);

if (in_array($customer_email, $email_array))
return true;
else
return false;




Not sure how to merge these two into one.










share|improve this question


























  • @helgatheviking you would not be able to help with this?

    – user11256696
    Mar 28 at 10:57











  • Just for info: Re-enable deleted answer and updated… check it please.

    – LoicTheAztec
    Mar 29 at 0:20













2












2








2


1






By checking the GUEST customer's email address against processing and completed orders, I want to give the GUEST a "first order discount" if the email has no orders. It would be nice if this could happen as the guest types in their email.



I think I've managed to make the discount code and now I am asking for help on merging these two codes, making it all work.



Here's the discount code:



add_action( 'woocommerce_cart_calculate_fees', 'first_time_order_discount', 10, 1 );
function first_time_order_discount( $wc_cart )

if ( is_admin() && ! defined('DOING_AJAX') ) return;

// discount percentage, change this into whatever you like
// currently set to 5%
$percent = 5;

// calculate first order discount based on the percentage above
$first_order_discount = $wc_cart->cart_contents_total * $percent / 100;
$wc_cart->add_fee( __( 'First Order Discount', 'woocommerce')." ($percent%)", -$first_order_discount );



And here's the control code:



function has_bought( $customer_email )
$orders = get_posts( array(
'numberposts' => -1,
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed'),
) );

$email_array = array();

foreach($orders as $order)
$order_obj = wc_get_order($order->ID);
$order_obj_data = $order_obj->get_data();
array_push($email_array, $order_obj_data['billing']['email']);

if (in_array($customer_email, $email_array))
return true;
else
return false;




Not sure how to merge these two into one.










share|improve this question
















By checking the GUEST customer's email address against processing and completed orders, I want to give the GUEST a "first order discount" if the email has no orders. It would be nice if this could happen as the guest types in their email.



I think I've managed to make the discount code and now I am asking for help on merging these two codes, making it all work.



Here's the discount code:



add_action( 'woocommerce_cart_calculate_fees', 'first_time_order_discount', 10, 1 );
function first_time_order_discount( $wc_cart )

if ( is_admin() && ! defined('DOING_AJAX') ) return;

// discount percentage, change this into whatever you like
// currently set to 5%
$percent = 5;

// calculate first order discount based on the percentage above
$first_order_discount = $wc_cart->cart_contents_total * $percent / 100;
$wc_cart->add_fee( __( 'First Order Discount', 'woocommerce')." ($percent%)", -$first_order_discount );



And here's the control code:



function has_bought( $customer_email )
$orders = get_posts( array(
'numberposts' => -1,
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed'),
) );

$email_array = array();

foreach($orders as $order)
$order_obj = wc_get_order($order->ID);
$order_obj_data = $order_obj->get_data();
array_push($email_array, $order_obj_data['billing']['email']);

if (in_array($customer_email, $email_array))
return true;
else
return false;




Not sure how to merge these two into one.







php jquery ajax wordpress woocommerce






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 29 at 0:21









LoicTheAztec

109k15 gold badges92 silver badges131 bronze badges




109k15 gold badges92 silver badges131 bronze badges










asked Mar 27 at 22:15







user11256696






















  • @helgatheviking you would not be able to help with this?

    – user11256696
    Mar 28 at 10:57











  • Just for info: Re-enable deleted answer and updated… check it please.

    – LoicTheAztec
    Mar 29 at 0:20

















  • @helgatheviking you would not be able to help with this?

    – user11256696
    Mar 28 at 10:57











  • Just for info: Re-enable deleted answer and updated… check it please.

    – LoicTheAztec
    Mar 29 at 0:20
















@helgatheviking you would not be able to help with this?

– user11256696
Mar 28 at 10:57





@helgatheviking you would not be able to help with this?

– user11256696
Mar 28 at 10:57













Just for info: Re-enable deleted answer and updated… check it please.

– LoicTheAztec
Mar 29 at 0:20





Just for info: Re-enable deleted answer and updated… check it please.

– LoicTheAztec
Mar 29 at 0:20












1 Answer
1






active

oldest

votes


















1















To check customer (guest or not) orders from "Billing email" user live input requires Javascript and Ajax to enable (apply) a cart discount (a negative fee) on checkout page.



The complete code:



// Conditionally apply a percentage discount if customer has already make a purchase
add_action( 'woocommerce_cart_calculate_fees', 'first_time_purchase_percentage_discount', 10, 1 );
function first_time_purchase_percentage_discount( $cart )
$percent = 5; // HERE set the discount percentage (float)

if ( is_admin() && ! defined('DOING_AJAX') )
return;

if ( WC()->session->get( 'first_purchase_discount' ) && is_checkout() )
// The First order discount percentage calulation
$first_order_discount = $cart->get_subtotal() * $percent / 100;

// Apply the discount
$cart->add_fee( __( 'First Order Discount', 'woocommerce')." ($percent%)", -$first_order_discount );



// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_checkout_billing_email', 'get_ajax_checkout_billing_email' );
add_action( 'wp_ajax_nopriv_checkout_billing_email', 'get_ajax_checkout_billing_email' );
function get_ajax_checkout_billing_email()
// Checking that the posted email is valid
if ( isset($_POST['cb_email']) && filter_var($_POST['cb_email'], FILTER_VALIDATE_EMAIL) )
// Get one of customer orders from billing email
$orders = get_posts( array(
'numberposts' => 1, // Just one is enough
'meta_key' => '_billing_email',
'meta_value' => sanitize_email( $_POST['cb_email'] ),
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed')
) );

// If the inputed billing email is not set on a customer order we set the value to TRUE
$value = sizeof($orders) == 0 && ! empty($_POST['cb_email']) ? true : false;

// Set the value in custom Woocommerce session identifier
WC()->session->set('first_purchase_discount', $value );

// Return the session value to jQuery
echo WC()->session->get('first_purchase_discount');

die();


add_action('wp_footer', 'checkout_billing_email_js_ajax' );
function checkout_billing_email_js_ajax()
// Only on Checkout
if( is_checkout() && ! is_wc_endpoint_url() ) :

// Initializing
WC()->session->set('first_purchase_discount', false);
?>
<script type="text/javascript">
jQuery(function($)
if (typeof wc_checkout_params === 'undefined')
return false;

$( 'input#billing_email' ).on('change blur', function()
var value = $(this).val();
console.log(value);
$.ajax(
type: 'POST',
url: wc_checkout_params.ajax_url,
data:
'action': 'checkout_billing_email',
'cb_email': value,
,
success: function (result)
if( result == 1 )
// Update checkout
$(document.body).trigger('update_checkout');

console.log(result); // For testing (to be removed)

);
);
);
</script>
<?php
endif;



Code goes in function.php file of your active child theme (or active theme). Tested and works.




Addition:



To handle "on hold" status too, replace the following line:



'post_status' => array('wc-processing', 'wc-completed')


by this:



'post_status' => array('wc-on-hold', 'wc-processing', 'wc-completed')





share|improve this answer



























  • thank you, very kind of you to help. I'm not sure if this falls under the "new question" rule, but is it possible to add a text above the email field informing the user that the discount has been applied? It's easy to "miss" otherwise. Again, thank you very much.

    – user11256696
    Mar 29 at 0:42






  • 1





    of course, I've upvoted and accepted. Again, thank you. Here's the new question. Kindly have a look. stackoverflow.com/questions/55409078/…

    – user11256696
    Mar 29 at 1:03










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387296%2ffirst-order-discount-for-guest-customers-checking-woocommerce-orders-billing-ema%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown
























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1















To check customer (guest or not) orders from "Billing email" user live input requires Javascript and Ajax to enable (apply) a cart discount (a negative fee) on checkout page.



The complete code:



// Conditionally apply a percentage discount if customer has already make a purchase
add_action( 'woocommerce_cart_calculate_fees', 'first_time_purchase_percentage_discount', 10, 1 );
function first_time_purchase_percentage_discount( $cart )
$percent = 5; // HERE set the discount percentage (float)

if ( is_admin() && ! defined('DOING_AJAX') )
return;

if ( WC()->session->get( 'first_purchase_discount' ) && is_checkout() )
// The First order discount percentage calulation
$first_order_discount = $cart->get_subtotal() * $percent / 100;

// Apply the discount
$cart->add_fee( __( 'First Order Discount', 'woocommerce')." ($percent%)", -$first_order_discount );



// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_checkout_billing_email', 'get_ajax_checkout_billing_email' );
add_action( 'wp_ajax_nopriv_checkout_billing_email', 'get_ajax_checkout_billing_email' );
function get_ajax_checkout_billing_email()
// Checking that the posted email is valid
if ( isset($_POST['cb_email']) && filter_var($_POST['cb_email'], FILTER_VALIDATE_EMAIL) )
// Get one of customer orders from billing email
$orders = get_posts( array(
'numberposts' => 1, // Just one is enough
'meta_key' => '_billing_email',
'meta_value' => sanitize_email( $_POST['cb_email'] ),
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed')
) );

// If the inputed billing email is not set on a customer order we set the value to TRUE
$value = sizeof($orders) == 0 && ! empty($_POST['cb_email']) ? true : false;

// Set the value in custom Woocommerce session identifier
WC()->session->set('first_purchase_discount', $value );

// Return the session value to jQuery
echo WC()->session->get('first_purchase_discount');

die();


add_action('wp_footer', 'checkout_billing_email_js_ajax' );
function checkout_billing_email_js_ajax()
// Only on Checkout
if( is_checkout() && ! is_wc_endpoint_url() ) :

// Initializing
WC()->session->set('first_purchase_discount', false);
?>
<script type="text/javascript">
jQuery(function($)
if (typeof wc_checkout_params === 'undefined')
return false;

$( 'input#billing_email' ).on('change blur', function()
var value = $(this).val();
console.log(value);
$.ajax(
type: 'POST',
url: wc_checkout_params.ajax_url,
data:
'action': 'checkout_billing_email',
'cb_email': value,
,
success: function (result)
if( result == 1 )
// Update checkout
$(document.body).trigger('update_checkout');

console.log(result); // For testing (to be removed)

);
);
);
</script>
<?php
endif;



Code goes in function.php file of your active child theme (or active theme). Tested and works.




Addition:



To handle "on hold" status too, replace the following line:



'post_status' => array('wc-processing', 'wc-completed')


by this:



'post_status' => array('wc-on-hold', 'wc-processing', 'wc-completed')





share|improve this answer



























  • thank you, very kind of you to help. I'm not sure if this falls under the "new question" rule, but is it possible to add a text above the email field informing the user that the discount has been applied? It's easy to "miss" otherwise. Again, thank you very much.

    – user11256696
    Mar 29 at 0:42






  • 1





    of course, I've upvoted and accepted. Again, thank you. Here's the new question. Kindly have a look. stackoverflow.com/questions/55409078/…

    – user11256696
    Mar 29 at 1:03















1















To check customer (guest or not) orders from "Billing email" user live input requires Javascript and Ajax to enable (apply) a cart discount (a negative fee) on checkout page.



The complete code:



// Conditionally apply a percentage discount if customer has already make a purchase
add_action( 'woocommerce_cart_calculate_fees', 'first_time_purchase_percentage_discount', 10, 1 );
function first_time_purchase_percentage_discount( $cart )
$percent = 5; // HERE set the discount percentage (float)

if ( is_admin() && ! defined('DOING_AJAX') )
return;

if ( WC()->session->get( 'first_purchase_discount' ) && is_checkout() )
// The First order discount percentage calulation
$first_order_discount = $cart->get_subtotal() * $percent / 100;

// Apply the discount
$cart->add_fee( __( 'First Order Discount', 'woocommerce')." ($percent%)", -$first_order_discount );



// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_checkout_billing_email', 'get_ajax_checkout_billing_email' );
add_action( 'wp_ajax_nopriv_checkout_billing_email', 'get_ajax_checkout_billing_email' );
function get_ajax_checkout_billing_email()
// Checking that the posted email is valid
if ( isset($_POST['cb_email']) && filter_var($_POST['cb_email'], FILTER_VALIDATE_EMAIL) )
// Get one of customer orders from billing email
$orders = get_posts( array(
'numberposts' => 1, // Just one is enough
'meta_key' => '_billing_email',
'meta_value' => sanitize_email( $_POST['cb_email'] ),
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed')
) );

// If the inputed billing email is not set on a customer order we set the value to TRUE
$value = sizeof($orders) == 0 && ! empty($_POST['cb_email']) ? true : false;

// Set the value in custom Woocommerce session identifier
WC()->session->set('first_purchase_discount', $value );

// Return the session value to jQuery
echo WC()->session->get('first_purchase_discount');

die();


add_action('wp_footer', 'checkout_billing_email_js_ajax' );
function checkout_billing_email_js_ajax()
// Only on Checkout
if( is_checkout() && ! is_wc_endpoint_url() ) :

// Initializing
WC()->session->set('first_purchase_discount', false);
?>
<script type="text/javascript">
jQuery(function($)
if (typeof wc_checkout_params === 'undefined')
return false;

$( 'input#billing_email' ).on('change blur', function()
var value = $(this).val();
console.log(value);
$.ajax(
type: 'POST',
url: wc_checkout_params.ajax_url,
data:
'action': 'checkout_billing_email',
'cb_email': value,
,
success: function (result)
if( result == 1 )
// Update checkout
$(document.body).trigger('update_checkout');

console.log(result); // For testing (to be removed)

);
);
);
</script>
<?php
endif;



Code goes in function.php file of your active child theme (or active theme). Tested and works.




Addition:



To handle "on hold" status too, replace the following line:



'post_status' => array('wc-processing', 'wc-completed')


by this:



'post_status' => array('wc-on-hold', 'wc-processing', 'wc-completed')





share|improve this answer



























  • thank you, very kind of you to help. I'm not sure if this falls under the "new question" rule, but is it possible to add a text above the email field informing the user that the discount has been applied? It's easy to "miss" otherwise. Again, thank you very much.

    – user11256696
    Mar 29 at 0:42






  • 1





    of course, I've upvoted and accepted. Again, thank you. Here's the new question. Kindly have a look. stackoverflow.com/questions/55409078/…

    – user11256696
    Mar 29 at 1:03













1














1










1









To check customer (guest or not) orders from "Billing email" user live input requires Javascript and Ajax to enable (apply) a cart discount (a negative fee) on checkout page.



The complete code:



// Conditionally apply a percentage discount if customer has already make a purchase
add_action( 'woocommerce_cart_calculate_fees', 'first_time_purchase_percentage_discount', 10, 1 );
function first_time_purchase_percentage_discount( $cart )
$percent = 5; // HERE set the discount percentage (float)

if ( is_admin() && ! defined('DOING_AJAX') )
return;

if ( WC()->session->get( 'first_purchase_discount' ) && is_checkout() )
// The First order discount percentage calulation
$first_order_discount = $cart->get_subtotal() * $percent / 100;

// Apply the discount
$cart->add_fee( __( 'First Order Discount', 'woocommerce')." ($percent%)", -$first_order_discount );



// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_checkout_billing_email', 'get_ajax_checkout_billing_email' );
add_action( 'wp_ajax_nopriv_checkout_billing_email', 'get_ajax_checkout_billing_email' );
function get_ajax_checkout_billing_email()
// Checking that the posted email is valid
if ( isset($_POST['cb_email']) && filter_var($_POST['cb_email'], FILTER_VALIDATE_EMAIL) )
// Get one of customer orders from billing email
$orders = get_posts( array(
'numberposts' => 1, // Just one is enough
'meta_key' => '_billing_email',
'meta_value' => sanitize_email( $_POST['cb_email'] ),
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed')
) );

// If the inputed billing email is not set on a customer order we set the value to TRUE
$value = sizeof($orders) == 0 && ! empty($_POST['cb_email']) ? true : false;

// Set the value in custom Woocommerce session identifier
WC()->session->set('first_purchase_discount', $value );

// Return the session value to jQuery
echo WC()->session->get('first_purchase_discount');

die();


add_action('wp_footer', 'checkout_billing_email_js_ajax' );
function checkout_billing_email_js_ajax()
// Only on Checkout
if( is_checkout() && ! is_wc_endpoint_url() ) :

// Initializing
WC()->session->set('first_purchase_discount', false);
?>
<script type="text/javascript">
jQuery(function($)
if (typeof wc_checkout_params === 'undefined')
return false;

$( 'input#billing_email' ).on('change blur', function()
var value = $(this).val();
console.log(value);
$.ajax(
type: 'POST',
url: wc_checkout_params.ajax_url,
data:
'action': 'checkout_billing_email',
'cb_email': value,
,
success: function (result)
if( result == 1 )
// Update checkout
$(document.body).trigger('update_checkout');

console.log(result); // For testing (to be removed)

);
);
);
</script>
<?php
endif;



Code goes in function.php file of your active child theme (or active theme). Tested and works.




Addition:



To handle "on hold" status too, replace the following line:



'post_status' => array('wc-processing', 'wc-completed')


by this:



'post_status' => array('wc-on-hold', 'wc-processing', 'wc-completed')





share|improve this answer















To check customer (guest or not) orders from "Billing email" user live input requires Javascript and Ajax to enable (apply) a cart discount (a negative fee) on checkout page.



The complete code:



// Conditionally apply a percentage discount if customer has already make a purchase
add_action( 'woocommerce_cart_calculate_fees', 'first_time_purchase_percentage_discount', 10, 1 );
function first_time_purchase_percentage_discount( $cart )
$percent = 5; // HERE set the discount percentage (float)

if ( is_admin() && ! defined('DOING_AJAX') )
return;

if ( WC()->session->get( 'first_purchase_discount' ) && is_checkout() )
// The First order discount percentage calulation
$first_order_discount = $cart->get_subtotal() * $percent / 100;

// Apply the discount
$cart->add_fee( __( 'First Order Discount', 'woocommerce')." ($percent%)", -$first_order_discount );



// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_checkout_billing_email', 'get_ajax_checkout_billing_email' );
add_action( 'wp_ajax_nopriv_checkout_billing_email', 'get_ajax_checkout_billing_email' );
function get_ajax_checkout_billing_email()
// Checking that the posted email is valid
if ( isset($_POST['cb_email']) && filter_var($_POST['cb_email'], FILTER_VALIDATE_EMAIL) )
// Get one of customer orders from billing email
$orders = get_posts( array(
'numberposts' => 1, // Just one is enough
'meta_key' => '_billing_email',
'meta_value' => sanitize_email( $_POST['cb_email'] ),
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed')
) );

// If the inputed billing email is not set on a customer order we set the value to TRUE
$value = sizeof($orders) == 0 && ! empty($_POST['cb_email']) ? true : false;

// Set the value in custom Woocommerce session identifier
WC()->session->set('first_purchase_discount', $value );

// Return the session value to jQuery
echo WC()->session->get('first_purchase_discount');

die();


add_action('wp_footer', 'checkout_billing_email_js_ajax' );
function checkout_billing_email_js_ajax()
// Only on Checkout
if( is_checkout() && ! is_wc_endpoint_url() ) :

// Initializing
WC()->session->set('first_purchase_discount', false);
?>
<script type="text/javascript">
jQuery(function($)
if (typeof wc_checkout_params === 'undefined')
return false;

$( 'input#billing_email' ).on('change blur', function()
var value = $(this).val();
console.log(value);
$.ajax(
type: 'POST',
url: wc_checkout_params.ajax_url,
data:
'action': 'checkout_billing_email',
'cb_email': value,
,
success: function (result)
if( result == 1 )
// Update checkout
$(document.body).trigger('update_checkout');

console.log(result); // For testing (to be removed)

);
);
);
</script>
<?php
endif;



Code goes in function.php file of your active child theme (or active theme). Tested and works.




Addition:



To handle "on hold" status too, replace the following line:



'post_status' => array('wc-processing', 'wc-completed')


by this:



'post_status' => array('wc-on-hold', 'wc-processing', 'wc-completed')






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 28 at 8:50

























answered Mar 27 at 23:04









LoicTheAztecLoicTheAztec

109k15 gold badges92 silver badges131 bronze badges




109k15 gold badges92 silver badges131 bronze badges















  • thank you, very kind of you to help. I'm not sure if this falls under the "new question" rule, but is it possible to add a text above the email field informing the user that the discount has been applied? It's easy to "miss" otherwise. Again, thank you very much.

    – user11256696
    Mar 29 at 0:42






  • 1





    of course, I've upvoted and accepted. Again, thank you. Here's the new question. Kindly have a look. stackoverflow.com/questions/55409078/…

    – user11256696
    Mar 29 at 1:03

















  • thank you, very kind of you to help. I'm not sure if this falls under the "new question" rule, but is it possible to add a text above the email field informing the user that the discount has been applied? It's easy to "miss" otherwise. Again, thank you very much.

    – user11256696
    Mar 29 at 0:42






  • 1





    of course, I've upvoted and accepted. Again, thank you. Here's the new question. Kindly have a look. stackoverflow.com/questions/55409078/…

    – user11256696
    Mar 29 at 1:03
















thank you, very kind of you to help. I'm not sure if this falls under the "new question" rule, but is it possible to add a text above the email field informing the user that the discount has been applied? It's easy to "miss" otherwise. Again, thank you very much.

– user11256696
Mar 29 at 0:42





thank you, very kind of you to help. I'm not sure if this falls under the "new question" rule, but is it possible to add a text above the email field informing the user that the discount has been applied? It's easy to "miss" otherwise. Again, thank you very much.

– user11256696
Mar 29 at 0:42




1




1





of course, I've upvoted and accepted. Again, thank you. Here's the new question. Kindly have a look. stackoverflow.com/questions/55409078/…

– user11256696
Mar 29 at 1:03





of course, I've upvoted and accepted. Again, thank you. Here's the new question. Kindly have a look. stackoverflow.com/questions/55409078/…

– user11256696
Mar 29 at 1:03








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387296%2ffirst-order-discount-for-guest-customers-checking-woocommerce-orders-billing-ema%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현