WP redirect users from dashboard but admins

WP redirect users from dashboard but admins

So one thing that really annoys me of WP is when you have your site and you have registration open for users they get also a dashboard, this is true even for Buddypress, well let’s try to fix this let’s redirect the non admin when they click the link on top to go to their dashboard, they instead will get redirected back to the home website.

In order for this to work , either you do it as plugin (overkilled) of if you have Buddypress then you can insert it in “bp-custom.php” file if it doesn’t exist then you can create it, Buddypress execute “bp-custom.php” when the site is loading..

Now if you only have WP installed then you can place it in your theme’s “function.php” one caveat is that if you update your theme it will be overwritten and we don’t want that, do we? , what we can do is create a WordPress Child Theme and insert it there but also for something that little is overkill.

Whichever method you decide to use take in account if you do it directly in the Theme function that when it gets an update it will remove the changes you have, can’t be stressed so much… As for me what I did is create a simple plugin where I place all little codes when I need to make WP or BP behave differently or change somethings without changing code directly.

So let’s create a folder, name it as you wish.. I gonna give it a name “wp-bp-custom-code-insertions” in it, create a PHP file and name it as its folder.. When done, them insert this code in it.

<?php
/*
 * Plugin Name: wp bp custom code insertion
 * Plugin URI: http://www.techuserspace.com
 * Description: Do you have code snippets? then place them in this plugin.
 * Author: TehcUserSpace/Neumann Valle
 * Author URI: http://www.techuserspace.com
 * Version: 1.0.0
 */

if (!defined("ABSPATH")) {
    exit(); // Exit if accessed directly
}

/**
 * redirects users from their dashboard
 * allows admins to still access Admin Page 
 */
function wp_bp_redirect_users_from_dashboard_but_admins()
{

    if (is_admin() && !current_user_can('administrator') && !(defined('DOING_AJAX') && DOING_AJAX)) {
        wp_redirect(home_url());
        exit();
    }
}
// now load it
add_action('admin_init', 'wp_bp_redirect_users_from_dashboard_but_admins');

Line 19 we defined

wp_bp_redirect_users_from_dashboard_but_admins

function. The function is_admin() checks we are in the dashboard, and then it checks the user browsing isn’t an Admin with the function

current_user_can('administrator') ;

then at last it checks if the process is doing Ajax calls to let them pass to admin.php. Then after it does all this checks finish with a redirection to Home URL wp_redirect(home_url()).

At line 28 then we add it to the WP loading process

add_action('admin_init', 'wp_bp_redirect_users_from_dashboard_but_admins');

That’s it, remember I am just a Tech User just like you. bye for now!