You can filter the login_redirect
function like so, adapt according to your needs.
add_filter('login_redirect', 'redirect_previous_page', 10, 1);
function redirect_previous_page( $redirect_to ){
global $user;
$request = $_SERVER["HTTP_REFERER"];
if ( in_array( $user->roles[0], array( 'administrator') ) ) {
return admin_url();
} elseif ( in_array( $user->roles[0], array( 'subscriber') ) ) {
return $request;
}
return $redirect_to;
}
Update 1:
Code (above) has been modified above and tested – it works.
Update 2: (by Tanya)
Chatted with @userabuser and came up with this answer that works.
// Redirect to previous page
remove_all_filters('login_redirect', 99);
add_filter('bbp_user_login_redirect_to', 'function_name');
Important note:
It turns out that Tanya was using the bbPress forum plugin, therefore despite the original snippet which uses,
add_filter('login_redirect', 'function_name'); //the standard WordPress API filter
which is correct and does work under “normal” WordPress conditions, was, in this case being overwritten in priority by the bbPress filter,
add_filter('bbp_user_login_redirect_to', 'function_name'); //the bbPress API filter
Now since the documentation on the bbPress.org website which details these actions and hooks is poorly organized and somewhat incomplete (far as I can tell), I suggest that (anyone) seeking further information about what hooks where and what filters what, should take a look at this resource here which provides a detailed list of hooks and filters.
Notes: (miscellaneous)
Change 'subscriber'
to match the role you are using for that type of user. It can also accept multiple roles since its in the form of an array.
in_array( $user->roles[0], array( 'subscriber', 'role2, role3', 'etc')