WooCommerce Redirect After Logout [Ultimate Guide]

WooCommerce redirect after logout WooCommerce redirect after logout can be created using the code in this post to redirect the WooCommerce customers to a specific page or post or an external URL after they logout. In this article, I want to demonstrate how to create this redirect with code. If you missed my previous tutorial, I illustrated how to create WooCommerce logout page shortcode, which can be a good place to start before you create the WooCommerce logout redirect.

There are plugins that can be used to create WooCommerce logout redirects but they are not as good as they should be; I am  working on a better solution that will help you manage the WooCommerce redirect after logout just like the plugin I created for the WooCommerce Logout After Checkout.

If you would like to be an early adopter, please get in touch with me, so that I can add you on the list since the plugin will be ready on 2 weeks from today.

For this post, I  want to share the code approach that you can use to create an efficient WooCommerce logout redirect but the plugin will have several conditional options that extend the default redirect options as I accomplished in the WooCommerce Redirect after checkout plugin.

Table of Contents

WooCommerce Logout Redirect Sections -Skim and Skip to Section

In most of my client projects I was having a tough time getting the logout redirect to work on a WooCommerce sites. For this reason, I decided to put together this ultimate guide of creating WooCommerce redirect after logout guide.

I hope  it can be a great place for both tech savvy and none tech savvy users to find solution for creating the best WooCommerce logout redirection option for their projects.

Since this is not an ordinary blog post, its is long and can take more time to read and understand every detail. I would like to help you skim through the different sections so that you can quickly pick the solution you need for your project.

WooCommerce Redirect After Logout

woocommerce logout redirectBy default, WooCommerce after logout, registration and login redirects users to the “my account”. This behavior is not desirable, especially on websites that are geared towards increasing their sales.

The three most common user management actions on your WooCommerce site include :

  • User Registration
  • User Login
  • User Registration
  • User Profile Edit
  • User Logout

Each of these actions can be improved to not only make it easier for the user to navigate smoothly but also increase the sales prospect for both new and existing customers. Woocommerce logout URL or link is by default located on My Account page and most WooCommerce store owners want to change the logout redirect on My account page to redirect to a specific page or WooCommerce sales funnel.

How to Redirect Logout from My Account page ?

One of the most common questions about WooCommerce logout is how to create an automatic logout from My Account page and redirect to another website or to an internal page.

This is the question that will be addressed and resolved in this post, by the end of this tutorial,you should comfortably create a custom WooCommerce logout redirect even with little or no prior coding knowledge.

woocommerce redirect after logout My Account Page

Why Create WooCommerce Logout Redirect

A good eCommerce website should harness all the opportunities to redirect users to the pages that can increase the sales and conversions after every action – login, logout, cart, checkout, registration etc.

Its about creating a good WooCommerce sales funnel to promote other products cross sales, down sales and other related products or best selling products.

WooCommerce logout redirects allows you to increase your sales conversion rate by redirecting customers after logout to a sales landing page or a strategic WooCommerce funnel redirect page — instead of redirecting the customer to the default “my account” page.

This tutorial will show you how to change the default setting of WooCommerce redirect after logout  and redirect users to custom URLs such as “sales funnels,” “special offers,” “catalog,” the previous page, special landing page or any external link that is suitable for increased sales and conversions.

In this post , I will share with you a quick tip on how to create custom redirect after WooCommerce logout just like I shared previously how to create WooCommerce redirect after checkout. Ideally, the default WooCommerce logout is not as smooth as it should be. It shows a confirmation message that is a nuisance to a number of users.

I discussed earlier how to remove WooCommerce logout confirmation message which makes it easier for your customers to automatically logout of your WooCommerce site without the conformation message popping up.

I also shared the WooCommerce logout code snippet that you can extend in this tutorial to make it more efficient by adding the redirect option, just like I did in the  WooCommerce redirect after checkout plugin that features conditional redirect options.

Change WooCommerce Logout Redirectchange woocommerce logout redirect

To change WooCommerce logout redirect is another important improvement of the  customer logout experience that you should consider, just like I illustrated how to add WooCommerce logout link to menu.

So lets us now delve deep into creating the best WooCommerce logout redirect option that you can immediately implement on your store to improve the user experience.

This option is simple since we need to use a filter to check logout event when it occurs.

When the WooCommerce logout occurs we can hook on this hook – woocommerce_login_redirect then pass a callback function with our redirect logic to the page where we want to redirect the user after logout.

If you are not familiar with the WooCommerce or WordPress action hooks and filter hooks, this tutorial on apply_filters and do_action hooks can be a good place to start to get accustomed with filters and hooks.

It is always a good practice before you begin creating the WooCommerce logout redirect function, you should check if the user is logged in.  Now let us outline the various options you can use to create WooCommerce logout redirect.

Each of these functions uses default WooCommerce and WordPress action hooks and functions that are discussed in detailed in the other sections of this tutorial.

Homepage Redirect – After Logout Redirect to Homepage in Woocommerce

One of the most common WooCommerce redirect after logout is to the home page. By default WooCommerce redirects to My Account page after the logout is completed.

If you wish to redirect the user to the homepage, you should consider adding this code to your functions.php file of the active WooCommerce theme.

Just copy this code into your theme functions.php file and test to see if the WooCommerce user is redirected to the home page after the logout.

Redirect to Homepage after Logout Snippet

You can also add this code snippet to the plugins file and it will work seamlessly.

add_action('wp_logout','njengah_homepage_logout_redirect');

function njengah_homepage_logout_redirect(){

    wp_redirect( home_url() );

    exit;

}

How Redirect Code Works

There are two functions and one action hook used in this code to create the WooCommerce redirect after logout as in the code above. Let’s keenly look at the role of each of these functions and hook:

Hook :  wp_logout

This code uses the wp_logout action hook that has been discussed in detail in this article under the – WordPress hook – wp_logout section. Ideally, this is a default WordPress logout hook that is fired after the logout has been executed.

Function : wp_redirect()

In this case if you look at the callback function if makes use of the wp_redirect() function that has also been explained in detail in the section wp_redirect WordPress function section.

Function:  home_url()

The final function used in the callback function is the home_url() , this is a WordPress function that returns the homepage url of the current site.

home_url( string $path = '', string|null $scheme = null )

For example you can display the homepage URL of the current site using the home_url() function as follows:

$url = home_url();

echo $url;

So in this case of the WooCommerce redirect after logout it will return the current site URL and add it as a string to the wp_redirect() function.

For us to understand how the WooCommerce logout redirect hook works as we apply it in your code we need to look at each of these default WordPress functions and the role they play in creating redirects.

Current Page Redirect – Woocommerce Logout Button and Redirect to Current Page

The second most common WooCommerce redirect after logout is the redirect to the current page after a user logouts out. This is important when you want to user to remain in the same page they were when they logged out.

In this case we need to know the page of the current user and apply it to the WooCommerce logout redirect logic.

To create WooCommerce redirect to the current page after the logout event we need to use the get_permalink() function to let us know the current page and then apply it to the logout callback function.

In this case you should add the following code snippet to your functions.php or your plugin files to execute the WooCommerce redirect after logout to the current page.

function njengah_redirect_current_page_after_logout( $logout_url, $redirect ){

       return $logout_url . '&redirect_to=' . get_permalink();

}

add_filter( 'logout_url', 'njengah_redirect_current_page_after_logout', 10, 2 );

How the Code Works

This code comprises of an filter hook logout_url and the callback function has the get_permalink() WordPress function that establishes the current page for the frontend users and uses it to return the logout URL.

Filter: logout_url()

In this case we have used logout_url which is another core WordPress and WooCommerce logout filter that has been discussed in detail in the section below WordPress function logout_url.

This code may not work for all the users and is likely to fail for the users in the admin backend. This is an appropriate redirect after logout for customers on My Account page but not for other roles.

To make it work for the users in the backend as well we need to replace the get_permalink() function with HTTP query value that represents the current page.

PHP Super Global $_SERVER[‘HTTP_HOST’]

So in that case we need to add this $_SERVER[‘HTTP_HOST’] super global as the alternative to the get_permalink() function. The $_SERVER is a PHP super global variable that contains information about headers, paths, and script locations.

The $_SERVER['HTTP_HOST'] super global returns the Host header from the current request. It therefore helps us to get the current page so that we can apply it to the WooCommerce redirect URL after logout.The new code that works for all the users should be as follows:

function njengah_redirect_current_page_after_logout( $logout_url, $redirect ){

      return $logout_url . '&redirect_to=http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

}

add_filter( 'logout_url', 'njengah_redirect_current_page_after_logout', 10, 2 );

You can now create a button to wrap up the redirect link by following the tutorial I shared previously on how to create WooCommerce logout button.

Specific Page Redirect – Woocommerce Logout Redirect Page (By ID)

In some cases you may want to redirect users to a specific page after they logout. The page can be added to the WooCommerce logout redirect logic using the page id.

In this case you need to know the page ID so that you pass it in the redirect function. You can achieve WooCommerce logout redirect to specific page by id using the following code snippet.

add_action('wp_logout','njengah_specific_page_logout_redirect');

function njengah_specific_page_logout_redirect(){

    wp_redirect( get_permalink($pageId) );

    exit;

}

How the Code Works

This code uses the wp_logout action hook and in the callback function we have the get_permalink() function with a variable $pageID which should be replaced by the ID of the page where you want to redirect the user after the checkout.

If you are not sure about the page ID you can use this post I wrote on how to get page ID in WordPress.

WooCommerce Function : wc_get_page_id()

You can also use the name of the page where you want to redirect the user along with the wc_get_page_id() WooCommerce function as in the code snippet below:

add_action('wp_logout','njengah_specific_page_logout_redirect');

function njengah_specific_page_logout_redirect(){

       wp_redirect( get_permalink( wc_get_page_id( 'shop' ) ) );

      exit;

}

The wc_get_page_id() function retrieve page ids and it commonly used for myaccount, edit_address, shop, cart, checkout, pay, view_order, terms and returns -1 if no page is found.

Customer Role Redirect – Woocommerce Customer Logout Redirect

Another WooCommerce redirect after logout scenario is where you want to redirect the users based on role. You probably want to redirect the customer to a given page after they logout instead of the default My Account redirect after logout.

In this case you can execute the redirect after logout for the customer role alone or another role or a group of roles using the code snippet shared below:

if( is_user_logged_in() ) { // check if there is a logged in user       

    $user = wp_get_current_user(); // getting & setting the current user

          $roles = ( array ) $user->roles; // obtaining the role

           // $roles[0]; // Returns one role

            //return $roles; // return array of the roles

             // Make the comparison here 

              if($roles[0] == 'customer'){

                 // Execute the redirect if the role of the current user is equal to customer

                    add_action('wp_logout','njengah_specific_page_logout_redirect');

                       function njengah_specific_page_logout_redirect(){

                        wp_redirect( get_permalink($pageId) );

                             exit;

                   }

           }

 }

How the Code Works

We have started by checking if the user is logged in as I explained in an earlier post on how to find if WordPress user is logged in.

Get the User Role

The second step was to get the role of the current user in WordPress using the wp_get_current_user() function and exacting the role of the current user.

Compare and Execute the Redirect If Role Matches Customer

The third step has been to now make the comparison of the role obtained in the previous step with the customer role and if the role matches you now add the redirect action and the function.

You can substitute the role with another other role including the custom roles. You can also change the redirect page by passing a different page Id in the get_permalink() function.

Previous Page Redirect- Woocommerce Logout Redirect to Previous Page

You can create WooCommerce redirect after logout to the previous page using the sessions. In this case you need to create a session and add it to a function and use it in the logic to create the redirect after logout to the previous page.

You can use the code snippet below to create the WooCommerce logout redirect to previous page:

// Start global session for saving the referer url
function start_session() {
     session_start();
}

add_action('init', 'start_session', 1);

// Get referer url and save it

function redirect_url() {
    if (is_user_logged_in()) {
        $_SESSION['referer_url'] = wp_get_referer();
    } else {
        session_destroy();
    }

}
add_action( 'template_redirect', 'redirect_url' );

//Logout redirect

function njengah_logout_redirect() {

    if (isset($_SESSION['referer_url'])) {

        wp_redirect($_SESSION['referer_url']);

    } else {

        wp_redirect(home_url());

    }

}

add_filter('wp_logout', 'njengah_logout_redirect', 1100, 2);

How the Code Works

This code used the PHP sessions to create a session and save the current page URL and in the redirect function we test for the set session URL – $_SESSION['referer_url'].

If it is set we create the redirect to that page as in the other logout redirects we discussed earlier.

My Account Page Redirect – Woocommerce My Account Logout Redirect

WooCommerce logout redirect from My Account page is one of the most commonly asked questions about WooCommerce logout.

This is not different from other logout redirect in fact you can add logout redirect on My Account page using the code snippet below:

add_action('wp_logout','njengah_my_account_page_logout_redirect');

function njengah_my_account_page_logout_redirect(){

       wp_redirect( get_permalink($pageId) );

                exit;

}

You can change the value of the $pageID variable in the get_permalink() function to correspond to the page ID of the redirect page or post and this will work seamlessly.

External URL Redirect- Woocommerce Logout Redirect Function Php Snippet:

If you would like to redirect users to an external URL after they logout from your WooCommerce store, you can accomplish this using a snippet added to the functions of your theme or in a custom plugin.

This WooCommerce logout redirect function php snippet that can be added to the functions.php file to create the redirect after logout is as follows:

add_action('wp_logout','njengah_redirect_after_logout');

function njengah_redirect_after_logout(){

  wp_redirect( $url);

  exit();

}

Simply add this code snippet in the functions.php and replace the $url variable with your respective redirect URL in quotes.

For example, if you want to redirect the user to an external URL after they logout and the external URL is http://example.com , you can replace the $url variable with the full URL as in the code below:

add_action('wp_logout','njengah_redirect_after_logout');

function njengah_redirect_after_logout(){

    wp_redirect( ‘http://example.com’);

    exit();

}

WP Logout Redirect URL – Woocommerce Logout URL

If you would like to create a WooCommerce logout button and place it in a custom template or in any other page, it helps you know the WP logout redirect URL that you can easily add on any button or link.

The following is the WP logout redirect URL that can be changed to any other page by changing the parameter ‘my-account’ “

wp_logout_url(

    get_permalink( wc_get_page_id( 'myaccount' ) )

 );

You can also have the external URL in the WooCommerce logout redirect URL as follows:

wp_logout_url(

   'http://example.com/'

);

You can also have the WordPress functions added to the WP logout redirect URL as follows:

wp_logout_url(

    home_url()

);

This WP logout redirect URL can be added in custom templates and can also be used in shortcodes or buttons to display a logout option in places that are not the default locations for the logout button, like widgets, footer, top bar menu and much more.

Fix Logout Redirect Error: Woocommerce Logout Redirect Not Working

If you have customized the WooCommerce logout redirect and it does not work, there is probably a bug in your code or one of the following reasons.

Hook Priority

The first step is to check the priority of your add_action() or add_filter() compared with the other WordPress hooks. This is one of the most common causes of the logout redirect error.

The higher the priority of the hook the earlier the loading occurs. If the two hooks have the same priority the one placed at the top of the other is loaded first. Adjusting the priority of the action or filter hook can be a good place to start your debugging.

Code Error – Syntax Error

The second step you need to check if all the code has an error and a common error is a syntax error. Possibly as you edit the code you can forget to place a closing quotation mark or a bracket.

Counter check the code and preferably add the code to a PHP syntax error checker.

It best if you are familiar with tools like Visual Studio or IDEs like Netbeans since these tools can quickly help you pick syntax errors in your code.

Code Added to Wrong File

Another common cause of the WooCommerce logout redirect not working error is when you have the right code but you add it in the wrong place. In this case if you are adding the code to a theme, it should strictly be added to the functions.php file.

When adding this code to a plugin you should be careful not to add it inside a class that is not instantiated. It is a good idea to add it to the plugin base file and to also fix any changes that may be required to ensure the code fits in the context of your custom plugin file structure.

Plugin or Theme Conflicts

In most cases there are plugins or themes that control the login and logout redirect in WooCommerce. These plugins can conflict leading to the logout redirect error.

If you are experiencing WooCommerce redirect logout error, you can start by deactivating all the plugins and using the default WordPress theme to check if the error if caused by a plugin or theme conflict.

Woocommerce Logout Redirect Plugin

Finally, nothing makes it easier to add WooCommerce redirect after logout than a well coded plugin with the right features, good user experience and world class support.  For years, I have fixed hundreds of logout, login and registrations issues on WooCommerce and WordPress in general.

In the last few weeks, I have put together all my experience and lessons learned about WooCommerce redirects and logout. I have built a remarkable WooCommerce logout redirect URL that comprises of the following features:

Logout Redirect Features

  • WooCommerce redirect after logout to any page – select page from a drop down list
  • WooCommerce redirect after logout to any single product – select product from a drop down list
  • WooCommerce redirect after logout to any single post – select post from a drop down list
  • WooCommerce redirect after logout to any product category – select product category from a drop down list
  • WooCommerce redirect after logout to current page
  • WooCommerce redirect after logout to previous page
  • WooCommerce redirect after logout to External URL
  • WooCommerce redirect after logout based on the role
  • WooCommerce redirect after logout based on purchase history ( suitable for special offers)
  • WooCommerce force logout after checkout

Login Redirect Features

  • WooCommerce redirect after login to any page – select page from a drop down list
  • WooCommerce redirect after login to any single product – select product from a drop down list
  • WooCommerce redirect after login to any single post – select post from a drop down list
  • WooCommerce redirect after login to any product category – select product category from a drop down list
  • WooCommerce redirect after login to current page
  • WooCommerce redirect after login to previous page
  • WooCommerce redirect after login to External URL
  • WooCommerce redirect after login based on the role
  • WooCommerce redirect after login based on purchase history (suitable for special offers)

WooCommerce Redirect after Login & Logout (WRAL) plugin is due for release in the coming few weeks. If you would like to be an early adopter do not be left behind since the launch will come with a 70% OFF discount.

You can join the list of the first 100 early adopters by getting in touch with me immediately. It’s due for release on 2nd November 2020.

Creating Logout Redirect In WordPress – Core Functions

After looking at the quick way to add snippets to create WooCommerce redirect after logout, it helps to highlight the default WordPress logout functions and hooks and explain in details for developers who are reading this guide to understand how these redirects works.

These functions and action hook can be useful for creating WooCommerce redirect after logout. In general you can create WooCommerce logout redirect using the following hooks and function:

I want to explain each of these functions and how you can use it to create WooCommerce redirect after checkout and why you may want to use one over the other.

It is also important to highlight the way you can create WooCommerce login redirect using filters. There is a function that is useful for creating login redirect in WooCommerce as well. Let us begin with the login redirect hook that is very useful for creating login redirect in WooCommerce.

WooCommerce Login Redirect :  woocommerce_login_redirect Hook

This is the special WooCommerce hook that allows us to control the login redirect functions in WooCommerce. It is similar to the default WordPress logout function that is applied in creating a WooCommerce redirect after logout. Its basic usage is as follows:

apply_filters( 'woocommerce_login_redirect',  $redirect,  $user );

As you can see it takes 2 parameters and the parameters are as follows:

Parameter Description Usage Example(s)
$redirect This is the redirect page where the user will land after the login.

It can be useful in changing the default WooCommerce redirect after login to allow user to land to the specific page after login.

add_filter('woocommerce_login_redirect', 'login_redirect')

You can add the filter hook and in the callback function you can pass the redirect logic as follows :

function login_redirect($redirect_to){
return home_url();
}

As you can see I have added the parameter $redirect_to and returned the redirect URL to redirect the user to the homepage after the login.

$user This is the user that the redirect action is applied to.

This can be particularly useful when you want to create a redirect after login for specific users.

Hook : woocommerce_login_redirect Not Working

This code can be used in the themes and plugin code but you need to understand the priorities to avoid firing to early or late where it will lead to the common scenario of woocommerce_login_redirect not working.

You also need to find out other reasons that can lead to woocommerce_login_redirect not working.  Of particular interest is another plugin that has a similar or same function that works before your code is fired.

So if you find out that woocommerce_login_redirect is not working., the first thing to check is the priority a case example you may have these two code snippets :

# Lower Priority 

add_filter( 'woocommerce_login_redirect', 'njengah_login_redirect', 1100, 2 );

# Higher Priority

add_filter( 'woocommerce_login_redirect', 'njengah_login_redirect', 10, 2 );

As you can see in both cases the priority numbers are different, the basic rule is that the smaller the number the higher the priority –meaning it loads first.

When you have this function used elsewhere in your theme or another plugin and you are trying to recreated the WooCommerce redirect after login or logout function, you need to pay attention to the priority. This is the solution to fix the woocommerce_login_redirect not working problem.

WordPress Logout Function – wp_logout_url()

This function is responsible for creating the logout URL in WordPress.

It helps developers and WordPress users to quickly create a logout URL that can be added to a link or button and I illustrated in this article – how to create WooCommerce logout URL.

WooCommerce extends the functionality by having the URL endpoints that play a crucial role in helping developers and users create WooCommerce logout page without any coding.

If you want to deeply understand the WooCommerce and WordPress logout process, it helps to begin by evaluating the wp_logout_url() function.

It’s a special function that you will come across it in several WordPress themes and plugins and it a good idea to get a glimpse of what is happening under the hood.

The basic usage of the function is as follows:

wp_logout_url( string $redirect = '' )

As you can see the function takes one parameter that is a string and the following are the details of the parameter:

Parameter Description Usage Example(s)   
$redirect This is a string parameter and it is optional to add it you can leave it blank and the function will work.

It is however useful in the case where you want to add a redirect URL to specific page.

So in this case the $redirect parameter is the URL of the redirect page, the destination where all the users who use this function in this context should land.

You can also pass other functions as parameters that strictly return a string since the wp_logout_url() only takes string as parameter.

You can use this function along with a link as follows :

<a href="<?php echo wp_logout_url(); ?>">Logout</a>

You can use this function and pass another function as a parameter that returns a string of the redirect URL as follows :

<a href="<?php echo wp_logout_url( home_url() ); ?>">Logout</a>

<a href="<?php echo wp_logout_url( get_permalink() ); ?>">Logout</a>

If you would like to understand the function further it helps to look at the defined code in the WordPress core. This core function code is as follows:

function wp_logout_url( $redirect = '' ) {
    $args = array();
    if ( ! empty( $redirect ) ) {
        $args['redirect_to'] = urlencode( $redirect );
    }
 
    $logout_url = add_query_arg( $args, site_url( 'wp-login.php?action=logout', 'login' ) );
    $logout_url = wp_nonce_url( $logout_url, 'log-out' );
 
    /**
     * Filters the logout URL.
     *
     * @since 2.8.0
     *
     * @param string $logout_url The HTML-encoded logout URL.
     * @param string $redirect   Path to redirect to on logout.
     */
    return apply_filters( 'logout_url', $logout_url, $redirect );
}

Action Hook : wp_logout

This is an action hook that is fired when the user has been logged out. It plays an important role in creating redirect after logout functionality.The basic usage of this function is as follows:

do_action( 'wp_logout', int $user_id )

As you can see it takes one parameter and the details of the parameter are as follows :

Parameter Description Usage Example(s)
$user_id This is the ID of the user who has been logged out. add_action('wp_logout','logout_redirect');

In this case we have added it as an action hook and we can pass our redirect after logout logic in the callback function as follows :

function logout_redirect(){

wp_redirect( home_url() );

exit;

}

So in this case we are redirecting the user after logout to the home page.

These functions are useful when you want to control the redirection of the user after they login or they logout.

WordPress Filter Hook logout_redirect

Another filter hook that you can use to create redirect after logout in WooCommerce is the Filter Hook logout_redirect. This filter hook works like wp_logout_url() function or wp_logout action hook.

It is a basic WordPress filter that is designed to help in creating WordPress or WooCommerce redirect after logout. Its basic usage is as follows:

apply_filters( 'logout_redirect', string $redirect_to, string $requested_redirect_to, WP_User $user )

As you can see it has three parameters and the parameter can be described in details as follows :

Parameter Description
$redirect_to This is the redirect destination URL and it must be a string, for example,  http://example.com
$requested_redirect_to This is the requested redirect destination URL that is passed as a parameter and it must also be a string just like the first parameter.
$user This is the user object – WP_User object of the user who has been logged out.

You can create a filter based WordPress redirect after logout using the logout_redirect as follows:

add_filter( 'login_redirect', 'njengah_logout_redirect', 10, 3 );

function njengah_logout_redirect( $location, $request, $user ) {

  global $user;

if ( isset( $user->roles ) && is_array( $user->roles ) ) {

   if ( in_array( 'subscriber', $user->roles ) ) {

       return home_url();

          } else {

        return $redirect_to;

      }

    }

   return;

}

WordPress Filter Hook login_redirect

It is also important to point out there is a similar filter for the login – login_redirect it works the same way as the logout_redirect  filter. In fact, the usage is similar and it comes with 3 parameters and the general expression is as follows:

apply_filters( 'login_redirect', string $redirect_to, string $requested_redirect_to, WP_User|WP_Error $user )

The parameters are similar expect the last parameter that has two user object options as you will see in the detailed description below:

Parameter Description
$redirect_to This is the redirect destination URL and it must be a string, for example,  http://example.com
$requested_redirect_to This is the requested redirect destination URL that is passed as a parameter and it must also be a string just like the first parameter.
$user This is the user object – WP_User object of the user who has been logged in if the login was successful but for unsuccessful login the WP_Error object is represented by this parameter

As you can see there are several ways you can use to create a WordPress or WooCommerce logout redirect.

In a quick summary we have highlighted the three most important hooks you should consider using for creating the redirect after logout. These hooks include:

  • Default WordPress logout_redirect – using filter to create redirect after logout
  • Action hook wp_logout – fired after the logout and thus can be used to create redirect.
  • WordPress logout function wp_logout_url() – WordPress default function that retrieves the logout URL and this can be useful in adding a redirect since it takes one parameter for the redirect path.

WooCommerce Multisite Redirect After Logout

When you are creating a redirect after logout in WooCommerce the wp_logout hook may fail to work when you have a multisite. In this case you need a little creativity to control how to create the WooCommerce redirect after logout.

In fact in a multisite set up WordPress logout function requires you to filter the allowed URLs for redirect and this can easily be executed using the allowed_redirect_hosts filter.

It helps to understand how this filter hook works so that you can use it in the WooCommerce multisite redirect after checkout. So let’s briefly look at this filter.

Filter Hook: allowed_redirect_hosts

This is a filter hook that filters all the allowed hosts to apply redirect to.  So in simple terms it checks the redirect URLs and vets them. The basic usage of this filter is as follows:

apply_filters( 'allowed_redirect_hosts', string[] $hosts, string $host )

As you can see in the expression above, it takes two parameter and they can be explained in details as follows:

Parameter Description Usage Example(s)
$hosts (string[]) This is simply an array with all the allowed host names add_filter( 'allowed_redirect_hosts', 'njengah_allow_parent_redirect' );

function njengah_allow_parent_redirect( $allowed ) {

$allowed[] = 'example.com'; // Multisite parent

return $allowed;

}

<a href="<?php echo wp_logout_url( 'http://example.com' ); ?>">Logout</a>

$host (string) This is the host name of the redirect destination.

This can be left empty.

You can add more hosts to the callback function and come up with code like this:

add_filter( 'allowed_redirect_hosts', 'njengah_allow_parent_redirect' );

function njengah_allow_parent_redirect( $allowed ) {
    $allowed = array(
    'blog.example.com',
    'codex.example.com',
     );
    return array_merge( $hosts, $allowed );
}

This simply serves the purpose of validating the allowed redirect URLs which is an important addition to multisites WooCommerce redirect after logout since in most case the default wp_logout redirect will fail without the filtering of the redirect hosts.

WordPress Redirect Function: wp_ Redirect

When you are creating redirect in WooCommerce or WordPress as I explained in the post on how to create redirect after checkout in WooCommerce, you need the wp_redirect() function.

Understanding the role of this function is crucial in creating WooCommerce redirect after checkout since it is the core function responsible for executing the redirects in WordPress and WooCommerce. Let us briefly outline how it works and the parameter it takes. The general usage of the wp_redirect() function is as follows:

wp_redirect( string $location, int $status = 302, string $x_redirect_by = 'WordPress' )

As you can see this function takes three parameters and they can be described in detail as follows:

Parameter Description
$location This is the path or URL where to redirect the user. It must be a string and it is required for the function to work.
$status This  is the HTTP response status code that should be applied to this redirect and this is an integer and it is optional to use it.
For example, you can add 301 for permanent redirect or you can leave it as the default value which is 302 which means moved temporarily.
$x_redirect_by This is the application that is doing the redirect and this by default is WordPress and should rarely be unset since we are creating WooCommerce redirect after logout which is within the context of WordPress.

Note

It is important to understand that when you are using the wp_redirect() function tit does not exit on its own. It is therefore important to always add exit after the function since the exit in PHP is used to terminate the current running script after the previous line of code is executed. So the best way to use wp_redirect function is as follows:

wp_redirect( $url );

exit

You can also create conditional redirect using the wp_redirect function with if statement as follows:

if ( wp_redirect( $url ) ) {

   exit;

}

This function can be used together with template_redirect hook as in the code below:

function njengah_wp_redirect_example() {

    if ( is_user_logged_in() && is_page( $id ) ){

        wp_redirect( get_permalink( $id ) );

        exit;

    }

}

add_action( 'template_redirect', 'njengah_wp_redirect_example' );

As you can see in the code above it can take a function as a parameter provided the function returns a string for the $location parameter as is the case with the get_permalink( ) function

WordPress Redirect Function: wp_safe_redirect()

The wp_safe_redirect() is the second WordPress redirect function that may be useful for executing the WooCommerce redirect after logout.This function works like the wp_redirect() function but it has an extra verification of the redirect URL.

In the wp_redirect function the $location parameter is not verified but in the wp_safe_redirect() function, the $location parameter is checked to ascertain if it is an allowed host.

That is the difference between the two redirect functions. The general usage of this redirect function is similar to that of the wp_redirect and the general expression is as follows:

wp_safe_redirect( string $location, int $status = 302, string $x_redirect_by = 'WordPress' )

As you can see the parameters are the same:

Parameter Description
$location This is the path or URL where to redirect the user. It must be a string and it is required for the function to work.
$status This is the HTTP response status code that should be applied to this redirect and this is an integer and it is optional to use it.
For example, you can add 301 for permanent redirect or you can leave it as the default value which is 302 which means moved temporarily.
$x_redirect_by This is the application that is doing the redirect and this by default is WordPress and should rarely be unset since we are creating WooCommerce redirect after logout which is within the context of WordPress.

This function allows plugin developers to set or remove the list of allowed hosts and if the host is not in the list of allowed hosts, the redirect fails and defaults to wp-admin.

Just like the wp_redirect function the wp_safe_redirect does not exit automatically and it also requires you to add exit as in the code snippets below:

wp_safe_redirect( $url );

exit;

You can also use it with conditional statement as in the previous example:

if ( wp_safe_redirect( $url ) ) {

    exit;

}

Conclusion

In this post, I outlined the step by step ways you can create the various WooCommerce redirect after logout options. I illustrated with code example how to create WordPress or WooCommerce redirect logout using the variety of available functions and hooks from WordPress core.

In a quick summary to sum up what we covered; how to create redirect after logout to:

  • Current page logout redirect
  • Previous page logout redirect
  • Homepage logout redirect
  • Specific page logout redirect
  • External URL logout redirect

I hope this guide gives you a great place to start while creating logout redirect in WooCommerce. If you would like to share feedback or contribute towards making this guide better and even point out mistakes or errors, feel free to get in touch with me.  If you like this guide you may also want to check out the other guide I wrote on how to create WooCommerce redirect after purchase.

Similar Articles

Best WooCommerce Plugins Lists