questions

Pass Woocommerce email field value to the functions.php

Rate this post

I’m trying to make a simple piece of code which will verify if the customers email is already in the database (we don’t want to allow to use the coupon without previous purchases).

I have following piece of code:

function check_coupon_code($coupon){
    
    $coupon_code = 'TEST';
    $found = false;

    // CHECK
    
    
    
    
    
    
    
    
    
    
    // CHECK END
    
    return $found;
}

//  Validity checking
add_filter( 'woocommerce_coupon_is_valid', 'is_it_valid', 10, 2);
function is_it_valid($valid, $coupon) {
    if( check_coupon_code( $coupon ) ){
        $valid = false;
    }
    return $valid;
}

// Validity checking error message
add_filter('woocommerce_coupon_error', 'coupon_returning_customer_error_message', 10, 3);
function coupon_returning_customer_error_message($err, $err_code, $coupon) {
    if( intval($err_code) === WC_COUPON::E_WC_COUPON_INVALID_FILTERED && check_coupon_code( $coupon ) ) {
        $err = __( "Coupon valid only for returning customers", "woocommerce" );
    }
    return $err;
}`

How I can pass the email provided in the billing_email field to the functions.php so I can use it on the backend?

///EDIT

// validation of adding coupons to cart
add_action( 'woocommerce_applied_coupon', 'coupon_returning_customer_error_message' );
function coupon_returning_customer_error_message($coupon_code) {
    // if the user is not logged in or has never made a purchase
    $order = new WC_Order($order_id);
    if (has_bought($order->get_billing_email())) {
        // removes the coupon
        WC()->cart->remove_coupon( $coupon_code );
        // clear the notices
        wc_clear_notices();
        // shows the error message
        wc_print_notice( sprintf( __( 'Coupon <strong>%s</strong> valid only for returning customers' ), $coupon_code ), 'error' );
    }
}

///FINAL VERSION

add_action( 'woocommerce_init', 'force_non_logged_user_wc_session' );
function force_non_logged_user_wc_session(){ 
    if( is_user_logged_in() || is_admin() )
       return;
    if ( isset(WC()->session) && ! WC()->session->has_session() ) 
       WC()->session->set_customer_session_cookie( true ); 
}

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();
            $.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');
                    }}});});});
    </script>
    <?php
    endif;
}

// 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) ) {
        // Set the value in custom Woocommerce session identifier
        WC()->session->set('email_session', sanitize_email( $_POST['cb_email'] ));
    }
    die();
}

// validation of adding coupons to cart
add_action( 'woocommerce_applied_coupon', 'coupon_returning_customer_error_message' );
function coupon_returning_customer_error_message($coupon_code) {
    
    function has_bought($value = 0) {
    global $wpdb;
    
    // Based on user ID (registered users)
    if ( is_numeric( $value) ) { 
        $meta_key   = '_customer_user';
        $meta_value = $value == 0 ? (int) get_current_user_id() : (int) $value;
    } 
    // Based on billing email (Guest users)
    else { 
        $meta_key   = '_billing_email';
        $meta_value = sanitize_email( $value );
    }
    $paid_order_statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );
   
    $count = $wpdb->get_var( $wpdb->prepare("
        SELECT COUNT(p.ID) FROM {$wpdb->prefix}posts AS p
        INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
        WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $paid_order_statuses ) . "' )
        AND p.post_type LIKE 'shop_order'
        AND pm.meta_key = '%s'
        AND pm.meta_value = %s
        LIMIT 1
    ", $meta_key, $meta_value ) );

    return $count > 0 ? true : false;
    }
    // if the user is not logged in or has never made a purchase
    if(! WC()->session->get('email_session')) {
        // removes the coupon
            WC()->cart->remove_coupon( $coupon_code );
            // clear the notices
            wc_clear_notices();
            // shows the error message
            wc_print_notice( sprintf( __( 'Enter email address to use coupon.' ), $coupon_code ), 'error' );
    } else {
        if (! has_bought(WC()->session->get('email_session'))) {
            // removes the coupon
            WC()->cart->remove_coupon( $coupon_code );
            // clear the notices
            wc_clear_notices();
            // shows the error message
            wc_print_notice( sprintf( __( 'Coupon valid only for returning customers.' ), $coupon_code ), 'error' );}
    }}

 

✔️Solution:

To check if a customer has placed at least one order (with the status wc-completed) you can use the conditional function has_bought() function from this answer and add it in your active theme’s functions.php file.

Then you can use the woocommerce_applied_coupon hook (which is triggered when a coupon has been applied) as follows:

// validation of adding coupons to cart
add_action( 'woocommerce_applied_coupon', 'coupon_returning_customer_error_message' );
function coupon_returning_customer_error_message( $coupon_code ) {
    // if the user is not logged in or has never made a purchase
    if ( ! has_bought() || ! is_user_logged_in() ) {
        // removes the coupon
        WC()->cart->remove_coupon( $coupon_code );
        // clear the notices
        wc_clear_notices();
        // shows the error message
        wc_print_notice( sprintf( __( 'Kupon <strong>%s</strong> jest ważny wyłącznie na ponowne zakupy' ), $coupon_code ), 'error' );
    }
}

The code has been tested and works. Add it to your active theme’s functions.php.

Leave a Reply

Your email address will not be published.

Back to top button