Site icon WP Smith

Hiding an User in the WordPress Admin

Sometimes it is good to hide a user from other users so that user won't be deleted or modified accidentally by another administrator. This especially good for hiding the hosting user or any machine/automation user.

Setup

So let's setup a plugin main file. Within wp-content/mu-plugins, add a file, hide-user.php.

<?php
/**
* Plugin Name: WPS User
* Plugin URI: https://wpsmith.net
* Description: User management.
* Author: Travis Smith <t@wpsmith.net>
* Author URI: https://wpsmith.net
* Text Domain: wps
* Domain Path: /languages
* Version: 0.1.0
*/
/**
* Plugin main file.
*
* @package WPS\Plugins\HideUser
* @author Travis Smith <t@wpsmith.net>
* @license GPL-2.0+
* @link https://wpsmith.net/
*/
namespace WPS\Plugins\HideUser;
view raw hide-user.php hosted with ❤ by GitHub

Now that we are setup, we can hide the user one of two ways:

  1. Using Composer in a Single File
  2. Putting All Code in a Single File

Mu-Plugin Using Composer

Create a composer.json file where we can require my user package (wpsmith/user) via composer.

{
"name": "wpsmith/hide-user",
"description": "Hides user in WordPress Admin.",
"type": "project",
"license": "GPLv2+",
"authors": [
{
"name": "Travis Smith",
"email": "t@wpsmith.net"
}
],
"minimum-stability": "dev",
"require": {
"wpsmith/user": "dev-master"
}
}
view raw composer.json hosted with ❤ by GitHub

Once we have this file, we can do a composer install which will install our packages into a folder called vendor automagically.

In the plugin file (hide-user.php), we need to require the composer autoloader.

namespace WPS\Plugins\HideUser;
// Require the composer autoloader.
require 'vendor/autoload.php';

Finally, we add the simple code to hide the user(s):

// Use the User Package & hide hidden_user1 & hidden_user2.
\WPS\User\HideUser::get_instance( array(
'hidden_user1',
'hidden_user2',
) );

Mu-Plugin with All Code

In the plugin file (hide-user.php), we need to add a hook into the pre_user_query.

namespace WPS\Plugins\HideUser;
add_action( 'pre_user_query', 'WPS\Plugins\HideUser\pre_user_query' );
/**
* Remove user from all user queries.
* @global \wpdb $wpdb WordPress database abstraction object.
*
* @param \WP_User_Query $user_search The current WP_User_Query instance,
* passed by reference.
*/
function pre_user_query( $user_search ) {
/**
* @var \WP_User $current_user \WP_User object for the current user.
*/
$current_user = wp_get_current_user();
if ( ! $current_user->exists() ) {
return;
}
// If the current user is not hidden_user1, let's remove hidden_user1.
if ( 'hidden_user1' !== $current_user->user_login ) {
global $wpdb;
// Now remove our hidden_user1 from the user query.
$user_search->query_where = str_replace(
'WHERE 1=1',
"WHERE 1=1 AND {$wpdb->users}.user_login != 'hidden_user1'",
$user_search->query_where
);
}
}

 

Credits: Image From Kristina Alexanderson.