Apanha

WooCommerce: Automatically Log Out Customers After Checkout

In WooCommerce, there are instances where it’s beneficial to log out a user after they complete a purchase. For instance, new customers, one-time buyers, or sites where accounts are only required temporarily may not benefit from keeping users logged in after checkout.

However, logging them out too early, such as immediately on the Checkout page or when the Thank You page loads, can prevent them from viewing their order details.


The ideal approach is to defer the logout until the user navigates away from the Thank You page. This ensures that checkout proceeds smoothly, the order confirmation is visible, and the user is safely logged out on their subsequent visit.


In this post, we’ll demonstrate a straightforward PHP snippet that accomplishes this using WooCommerce sessions. The code sets a logout flag after checkout and automatically logs the user out silently the next time they visit any page, maintaining a seamless and user-friendly experience.

--------

This PHP snippet employs a two-step process to securely log out users after they complete a WooCommerce checkout.


The first step is executed on the woocommerce_thankyou hook, which triggers when the order is successfully processed and the Thank You page is displayed. In this step, we set a session flag called logout_after_thankyou. This flag serves as a marker indicating that the user should be logged out the next time they visit any page on the site.


The second step is executed on the template_redirect hook, which runs every time a page is loaded. The code checks if the user is logged in and if the logout_after_thankyou flag is present in their session.

If both conditions are met, the user is logged out using WordPress wp_logout() function, and the WooCommerce session is cleaned up with WC()->session->cleanup_session(). Subsequently, the flag is removed to prevent the logout from occurring repeatedly.


This approach ensures that the user sees the Thank You page and their order details, but they are automatically logged out the next time they browse the site. It provides a seamless and user-friendly way to handle post-checkout logouts without disrupting the checkout process.

PHP:
/**
 * @snippet       Log Customers Out @ WooCommerce Thank You Page
 * @compatible    WooCommerce 10
 */
 
add_action( 'woocommerce_thankyou', 'nf_set_logout_after_checkout' );
 
function nf_set_logout_after_checkout( $order_id ) {
    if ( is_user_logged_in() ) {
        WC()->session->set( 'logout_after_thankyou', true );
    }
}
 
add_action( 'template_redirect', 'nf_logout_after_thankyou_silent' );
 
function nf_logout_after_thankyou_silent() {
    if ( is_user_logged_in() && WC()->session->get( 'logout_after_thankyou' ) ) {
        wp_logout();
        WC()->session->__unset( 'logout_after_thankyou' );
    }
}

You should place custom PHP in functions.php
 

Latest Activity New Uploads