W
WP Quick Search
Features Integration Pricing Documentation Blog Products Demo
Login Start for free
Login Start for free
Blog / WordPress/ How to Redirect Users After Login and Logout in WordPress

How to Redirect Users After Login and Logout in WordPress

2018-08-11 · Ryan · Post Comment
WordPress 登录与退出登录后自动跳转到指定页面的完整方法

Redirect After WordPress Login

To redirect users automatically after login, use the login_redirect filter hook. Add the following code to your theme's functions.php file:

function custom_login_redirect( $redirect_to, $request, $user ) {
    if ( is_a( $user, 'WP_User' ) && ! is_wp_error( $user ) ) {
        // Example: redirect to a 'dashboard' page
        return home_url( 'dashboard' );
    }
    return $redirect_to;
}
add_filter( 'login_redirect', 'custom_login_redirect', 10, 3 );

Using the home_url() Function

The home_url() function returns your site's root address. Provide only the path relative to the root or a query string inside the parentheses.

Correct examples:

  • home_url( 'dashboard' ) – redirects to https://yoursite.com/dashboard
  • home_url( 'category/news' ) – redirects to a category archive
  • home_url( '?page_id=2' ) – redirects using a page ID

Incorrect: home_url( 'https://yoursite.com/dashboard' ) – this creates a malformed URL.

Redirect After WordPress Logout

To redirect users after logout, use the wp_logout action hook. Add this code to your theme's functions.php:

function custom_logout_redirect() {
    // Example: redirect to the homepage
    wp_redirect( home_url() );
    exit();
}
add_action( 'wp_logout', 'custom_logout_redirect' );

Advanced Usage & Best Practices

  • Conditional Redirects: Add logic inside the function to redirect based on user roles.
  • Code Location: Always add code to a child theme's functions.php to prevent loss during updates.
  • Cache Consideration: Clear your browser and WordPress cache after making changes to see the effect.
  • Logout Hook: The wp_logout action fires after the user session is destroyed. wp_redirect() must be followed by exit().

Tip: Test redirects thoroughly, especially if using caching or security plugins.

CustomizationFunctions.phpHookslogin redirectlogout redirectUser ExperienceWordPress
Previous
How to Disable WordPress Automatic Updates and Hide Notifications
Next
How to Hide the WordPress Admin Bar on the Front End for Specific Users

Post a Comment Cancel reply

Your email will not be published. Required fields are marked with *.

Quick Navigation
W
WP Quick Search
About Terms of Service Privacy Policy
© 2026 WP Quick Search Inc. All rights reserved. ·
14 0.033s 4.23MB

Notice