WooCommerce Force Logout After Checkout & Register
Sometimes we may need to implement user approval in WordPress so that without approved any user can not login. Again, in woocommerce when someone checkout and account creating is enabled(that means guest checkout is disabled and user account creating is just the woocommerce checkout process), after checkout user is forced logged in and redirected to order received page whatever you are doing cash on delivery or real payment like paypal. So, in order received page user is actually in logged in mode, in woocommerce the checkout process actually creates the user and auto loggedin. Now, what we can do if we don’t want our user will be logged in but will be redirected the order received page ? Before we move for solution, in woocommerce’s settings for account and privacy there are different options to enabled disabled the user creations. One option is allowing user to create account or register from the my account page which has actually login form and register form for guest user. If user register from here still user will be auto logged in after successful registration.
Here are two solutions.
Disable automatic log-in when a new user registers(From My Account)
<code> add_filter( 'woocommerce_registration_auth_new_customer', '__return_false' ); </code>
Disable automatic log-in when a new user checkout
<code> // Logout after checkout and redirect to shop add_action( 'template_redirect', 'codeboxr_order_received_logout_redirect' ); /** * Re-Redirect user to order received page as guest user */ function codeboxr_order_received_logout_redirect() { // Only on "Order received" page if( is_wc_endpoint_url('order-received') ) { $cbxwcflo = isset($_REQUEST['cbxwcflo'])? absint($_REQUEST['cbxwcflo']) : 0; if(is_user_logged_in() && $cbxwcflo == 0){ wp_logout(); // Logout global $wp; // Get the order ID $order_id = absint( $wp->query_vars['order-received'] ); $key = isset($_REQUEST['key'])? wp_unslash($_REQUEST['key']) : ''; $order_received_url = wc_get_endpoint_url( 'order-received', $order_id, wc_get_checkout_url() ); $order_received_url = add_query_arg( 'key', $key, $order_received_url ); $order_received_url = add_query_arg( 'cbxwcflo', 1, $order_received_url ); if($order_id > 0 && $key != ''){ wp_redirect(apply_filters('codeboxr_order_received_logout_redirect_url', $order_received_url, $order_id, $key )); // Redirect to order received page } else{ // Shop redirection url $shop_url = get_permalink( get_option('woocommerce_shop_page_id') ); wp_redirect(apply_filters('codeboxr_order_received_logout_redirect_url', $shop_url, $order_id, $key)); // Redirect to shop } exit(); // Always exit }//end if }//end if order received page } </code>