Method 1
You could use login_redirect
filter to add login redirect url.
The filter pass 3 arguments
// refer to /wp-login.php
/**
* Filters the login redirect URL.
*
* @since 3.0.0
*
* @param string $redirect_to The redirect destination URL.
* @param string $requested_redirect_to The requested redirect destination URL passed as a parameter.
* @param WP_User|WP_Error $user WP_User object if login was successful, WP_Error object otherwise.
*/
The following example just pass the url, you can pass also $user argument and redirect according to different users.
add_filter( 'login_redirect', 'ws365094_logout_redirect_to', 10, 3 );
function ws365094_logout_redirect_to( $redirect_to_url, $requested_redirect_to, $user ) {
// any additional logic
return site_url( '/my-account' ); // just pass this url, after login, it will be redirected by WordPress original login routine
}
Method 2
If you have a custom login form, you may pass variable "redirect_to" because wp-login.php will check if there is any. If you redirect all to same url, this method is simpler than method 1.
<input type="hidden" name="redirect_to" value="somewhere_url" />
For your original logout method, you may also use logout_redirect
filter to add logout redirect url instead of template_redirect
action. template_redirect
is quite universal but more use cases in redirecting to specific template(template control). Just an additional notes for reference.
Sequence comparison between template_redirect
and login_redirect
According to the loading sequence. By default, after login, WordPress redirect the user to a specific page in order to get the cookie working which I have answered here before.
Login -> Redirect -> Template Redirect(canonical) which is normally done by redirect_canonical() if slug does not found, go to 404, if using /?p=111, check if permalink is in used, if so, direct to permalink structured url and so on
If using template_redirect
, it means the page is being handled in template-loader.php
. It becomes
Login -> Redirect -> Template Redirect(canonical) -> Custom Template Redirect
Because it follows do_action( 'template_redirect' ) in template loader which will load multiple times in this case. One way to optimize the script is that using a higher priority for the custom template_include
hook so that it check and redirect earlier functioning similar to Login Redirect.
Since reaching template_redirect
is a bit late of loading time. So it is still not an ideal place to do a user login checking and redirect to somewhere which is not template related matters.
So, unless necessary such as doing rewrite, custom URL structure or custom template preparation. Using it in later time is not recommended. Also, if redirect is handling unskilfully, it might also affect the SEO ranking. That's based on the actual loading sequence, SEO optimisation point of view and personal experience.
if ( ! is_user_logged_in() )