最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can we redirect user from login page to home page if user is logged in WordPress?

programmeradmin1浏览0评论

I have just installed WordPress locally in my computer and run the website successfully. I want to achieve following: when logged-in user tries to access wp-login.php or register page, it should be automatically redirected to home page.

I have spent several hours on web, but could no come up with solution neither was I able to find appropriate WordPress plugin.

My question is: why does WordPress function this way? how can we change this behavior as natively as simply as possible?

Thank you

I have just installed WordPress locally in my computer and run the website successfully. I want to achieve following: when logged-in user tries to access wp-login.php or register page, it should be automatically redirected to home page.

I have spent several hours on web, but could no come up with solution neither was I able to find appropriate WordPress plugin.

My question is: why does WordPress function this way? how can we change this behavior as natively as simply as possible?

Thank you

Share Improve this question edited Feb 27, 2021 at 17:47 Tornike Shavishvili asked Feb 27, 2021 at 16:48 Tornike ShavishviliTornike Shavishvili 1235 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

You can check the current page being loaded through the $pagenow global variable. Both login and registration is handled through wp-login.php. Adding this to the functions.php of your theme should work:

<?php

add_action('init', function () {

    if ($GLOBALS['pagenow'] === 'wp-login.php' && is_user_logged_in() && (!isset($_GET['action']) || $_GET['action'] !== 'logout')) {

        wp_redirect(home_url());
        exit;

    }

});

EDIT: Added a check to allow logging out and clarified where to put this code.

i modified @Patriot code.

I was able to achieve desired functionality with following code: I added this code to \wp-includes\functions.php at the and of file.

It not as clean is i wished, but it works.

If someone sees any possible issues with this approach, please inform us

add_action('init', function() {

    if ($GLOBALS['pagenow'] === 'wp-login.php' && is_user_logged_in()) {
        
        $defLoginPageActions = array(
            //'confirm_admin_email',
            //'postpass',
            'logout',
            //'lostpassword',
            //'retrievepassword',
            //'resetpass',
            //'rp',
            //'register',
            //'checkemail',
            //'confirmaction',
            //'login',
            WP_Recovery_Mode_Link_Service::LOGIN_ACTION_ENTERED,
        );
        $loginPageAction = isset( $_REQUEST['action'] ) ? $_REQUEST['action'] : '';

         
        if(!in_array( $loginPageAction, $defLoginPageActions)){  
            wp_redirect(home_url());
            exit;
        } 

    }
 
});
发布评论

评论列表(0)

  1. 暂无评论