Customize WordPress Registration and Login and Redirect Users to a Front-End User Center

More and more developers are adding user centers to WordPress sites so they can provide more functionality and retain more users. For advanced WordPress developers, this may not be a difficult task, but for beginners, building a front-end user center can feel a bit complicated. Below I have summarized several common problems I ran into while developing a WordPress user center, in case they are useful to anyone planning a similar front-end user center.

Only administrators can access the dashboard, and all other users are redirected to the user center

Once you have a front-end user center, there is no real need for non-admin users to access the default WordPress dashboard. After logging in, they can be sent directly to the front-end user center instead.

add_action( 'admin_init', 'redirect_non_admin_users' );
function redirect_non_admin_users() {
	if ( ! current_user_can( 'manage_options' ) && '/wp-admin/admin-ajax.php' != $_SERVER['PHP_SELF'] ) {
		wp_redirect( site_url("/me/") ); # "/me/" is the URL of the front-end user center.
		exit;
	}
}

One important detail in the code above is that $_SERVER['PHP_SELF'] returns the path after the domain name. If your WordPress site is installed in a subdirectory, then the /wp-admin/admin-ajax.php string must also include that subdirectory. Otherwise, Ajax requests will fail validation.

Show the admin bar only to administrators

If you have built a front-end user center, you usually do not want regular users to see any of the back-end interface. That said, the admin bar is still a very useful feature, so we only need to hide it for non-admin users.

if (!current_user_can('manage_options')) {
    add_filter('show_admin_bar', '__return_false');
}

Change the login page to a custom login page

One thing to note is that you should not directly link the login URL to the front-end user center login page. If you do that, logging out of the user center will automatically redirect the user back to the default login page.

function wizhi_login_page( $login_url, $redirect ) {
    $new_login_url = home_url('ucenter') . '?redirect_to=' . $redirect;
    return $new_login_url;
}
add_filter( 'login_url', 'wizhi_login_page', 10, 2 );

After handling the points above, the WordPress back end is basically hidden from regular users. However, one problem still remains: how do we hide the wp-login.php page itself? Users can still access the default login and registration page directly by visiting wp-login.php. If you already know a good solution, feel free to share it in the comments.

Related Posts

Leave a Reply

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