Lead Nerds

Play Video

How to allow WooCommerce existing customers to checkout without being logged in

In this video, we are going to show you how to allow WooCommerce existing customers to checkout without being logged in. This can also be a solution if you want a way for existing customers to checkout without logging in but want to have their orders attached to their WooCommerce accounts. This helps decrease abandoned carts and increases satisfaction and repeat purchases from your existing customers.

We found this problem when a customer wanted to place an order but had forgotten their password and couldn’t be bothered with resetting it. This would not be able to checkout at all with that particular email unless logged in they would of had to create a new email to use guest checkout.

The error shown says: An account is already registered with your email address. Please log in.

We want to bypass this message and allow them to check out immediately.

Here is a link to the Code Snippets Plugin mentioned in the video: https://wordpress.org/plugins/code-snippets/

 

Below is the code that needs to be added to the functions.php file of your WordPress website

<?php
// Allow WooCommerce existing customers to checkout without being logged in (allow orders from existing customers in WooCommerce without logging in)
function your_custom_function_name( $allcaps, $caps, $args ) {
	if ( isset( $caps[0] ) ) {
		switch ( $caps[0] ) {
		case 'pay_for_order' :
		$order_id = isset( $args[2] ) ? $args[2] : null;
		$order = wc_get_order( $order_id );
		$user = $order->get_user();
		$user_id = $user->ID;
		if ( ! $order_id ) {
		  $allcaps['pay_for_order'] = true;
		  break;
		}
		$order = wc_get_order( $order_id );
		if ( $order && ( $user_id == $order->get_user_id() || ! $order->get_user_id() ) ) {
		  $allcaps['pay_for_order'] = true;
		}
		break;
		}
	}
	return $allcaps;
}
add_filter( 'user_has_cap', 'your_custom_function_name', 10, 3 );
add_filter( 'woocommerce_checkout_posted_data', 'ftm_filter_checkout_posted_data', 10, 1 );
function ftm_filter_checkout_posted_data( $data ) {
	$email = $data['billing_email'];	
	if ( is_user_logged_in() ) {
	} else {
		if (email_exists( $email)){
			$user = get_user_by( 'email', $email );
			if ($user){
				$user_id = $user->ID;
				wc_set_customer_auth_cookie($user_id);
				session_start();
				$_SESSION['p33'] = "133";			
				$_SESSION['u'] = $user_id;			
				
			} else {
				$user_id = false;
			}
		}
	}
    return $data;
}
add_action( 'woocommerce_new_order', 'clearuser' );
function clearuser($data) {
	
	if ($_SESSION['p33']==133){
		//WC()->session->set('pp1',"0");
		nocache_headers();
		wp_clear_auth_cookie();		
		
		$yourSession= WP_Session_Tokens::get_instance($_SESSION['u']);
		$yourSession->destroy_all();		
		
		$_SESSION['p33']='';
		$_SESSION['u']='';
	}
}
//End Allow Woocommerce Order Pay Without LogIn

View more

Is There a Topic

You would like reviewed?