Can't access wordpress admin dashboard when blocking access to wp-admin and wp-login

I am having issues accessing the wordpress admin dashboard. I created a custom login page and blocked access to wp-admin and wp-login. Everything seems to be working up until I try to open the admin dashboard from the top ribbon. I can see I am logged in. I added the following debug code to the function that blocks wp_admin and wp_login. It checks if the current user is setup and is logged in. function block_pages() { $user = wp_get_current_user(); echo "USER: " . $user->user_login . "<br>"; echo "Logged in:" . is_user_logged_in(); ... } add_action( 'init', 'block_pages' ); When I go to the homepage (mydomain.com), it shows USER: <myuser> Logged in:1 When I click the ribbon to go to the admin dashboard, the page redirects to homepage and it shows USER: <blank> Logged in:<blank> I am hooking the block_pages() function to 'init'. However, it doesn't seem the wp_get_current_user() and is_user_logged_in() are available at that stage? I tried hooking it to 'plugins_loaded' and 'wp_loaded' with the same results. Any suggestion on how to resolve this issue? Thanks.

Comment (1)

Jese Leos

August 10, 2024

Verified user

I believe I figured out what is the problem. I thought the issue was with the block_pages() function. I eventually realized the issue was with my custom login page. I use wp_signon() to authenticate the user. This function does not set the current user and the auth cookie. I added the following code to my custom login function: ... $user = wp_signon( $creds, false ); if ( is_wp_error( $user ) ) { echo '<div class="error">' . $user->get_error_message() . '</div>'; } else { wp_set_current_user( $user->ID ); //added line wp_set_auth_cookie( $user->ID, true ); //added line wp_redirect( home_url() ); exit; } ... It is now working as intended. Leaving the answer here in case someone has a similar issue.

You’ll be in good company