Hasan
Hasan

Reputation: 159

Woocommerce Redirect Customers to Previous Page

I have applied all available snippets including this, but when customers log in, it redirects to My Account Page which is annoying. How to solve this?

Why doesn't below code work?

  add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );
  function wc_custom_user_redirect( $redirect, $user ) {

      $role = $user->roles[0];

    if ( $role == 'customer' ) {
      //Redirect to the previous visited page or, if not available, to home
         $redirect = wp_get_referer() ? wp_get_referer() : home_url();
    }
    return $redirect;
  }

Upvotes: 1

Views: 1496

Answers (1)

Ryszard Jędraszyk
Ryszard Jędraszyk

Reputation: 2412

First of all, wp_get_referer() at the point of woocommerce_login_redirect filter will target the account page and you need to get the referer of the referer. The second thing is that it doesn't work for me and many others, while $_SERVER['HTTP_REFERER'] grabs the referer without a problem.

This could be done using PHP sessions, but they cause problems on Ngix and Varnish with server caching.

The possible solutions are:

Pass a hidden referer URL field as shown here:

https://gist.github.com/EvanHerman/492c09fbb584e0c428ae

Use a database to temporarily store previous page URLs for each user ID. A query string with a unique ID is added to WooCommerce login form's URL. I use this solution in my plugin:

https://wordpress.org/plugins/extra-settings-for-woocommerce/

Upvotes: 1

Related Questions