woocommerce after login redirect

18,953

Solution 1

If you want to redirect after login :

<?php
/**
* Redirect users to custom URL based on their role after login
*
* @param string $redirect
* @param object $user
* @return string
*/
function wc_custom_user_redirect( $redirect, $user ) {
  // Get the first of all the roles assigned to the user
  $role = $user->roles[0];
  $dashboard = admin_url();
  $myaccount = get_permalink( wc_get_page_id( 'shop' ) );
  if( $role == 'administrator' ) {
    //Redirect administrators to the dashboard
    $redirect = $dashboard;
  } elseif ( $role == 'shop-manager' ) {
    //Redirect shop managers to the dashboard
    $redirect = $dashboard;
  } elseif ( $role == 'editor' ) {
    //Redirect editors to the dashboard
    $redirect = $dashboard;
  } elseif ( $role == 'author' ) {
    //Redirect authors to the dashboard
    $redirect = $dashboard;
  } elseif ( $role == 'customer' || $role == 'subscriber' ) {
    //Redirect customers and subscribers to the "My Account" page
    $redirect = $myaccount;
  } else {
    //Redirect any other role to the previous visited page or, if not available, to the home
    $redirect = wp_get_referer() ? wp_get_referer() : home_url();
  }
  return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 ); 

Solution 2

redirects for login / logout

add_filter('woocommerce_login_redirect', 'login_redirect');

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

add_action('wp_logout','logout_redirect');

function logout_redirect(){
    wp_redirect( home_url() );
    exit;
}
Share:
18,953
selva kumar
Author by

selva kumar

Updated on June 23, 2022

Comments

  • selva kumar
    selva kumar almost 2 years

    My In my woocommerce login form successful login it is redirection to shop page I did,

    And after login error it should be same page but it goes /wp-login.php.I got some codes but it is working when I enter wrong username or password but when I put empty user name or password it is going /wp-login.php.

    Here is the code

    function my_front_end_login_fail( $username,$password ){
        $referrer = $_SERVER['HTTP_REFERER'];
        if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ){
          wp_redirect( $referrer . '?login_failed=failed' );
          exit;
        }
    }
    

    Can you help me.