WP Smith

Creating WordPress & Genesis Websites Since 2010

  • Home
  • About
  • Services
  • Blog
  • Contact

Jan 09 2019

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 <[email protected]>
* 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 <[email protected]>
* @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": "[email protected]"
}
],
"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';
view raw hide-user-composer.php hosted with ❤ by GitHub

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',
) );
view raw hide-user-composer.php hosted with ❤ by GitHub

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
);
}
}
view raw hide-user-single-file.php hosted with ❤ by GitHub

 

Credits: Image From Kristina Alexanderson.

Written by Travis Smith · Categorized: Snippets

Sep 07 2015

Your Own WordPress Code Sandbox

When I was learning WordPress, the one file that I created that was the most helpful was my test.php file. This file proved extremely valuable. Even now, everyone once in a while, I want to write a vanilla function for a particular filter or action and see what the parameters contain. It was a way that I could load the WordPress environment (and optionally the admin environment) and test various default functions, filters, and actions. However, I don't want to navigate to a specific page or anything. I want something quick, easy and fast. So, I have this file that I keep in my development environment called test.php.

NEVER use this file in a production environment.

This file contains the following:

  1. Loads the WordPress Environment
  2. Contains debugging functions wps_printr() and wps_die()
  3. Optionally Loads the Admin Environment
  4. Optionally loads user functions
  5. Optionally loads the Plugins API

To use this file, create a file called test.php at the root of your local site (this is the same place where your wp-config.php [unless you have moved this file] and wp-load.php files are located. The file should be located and reachable by http://domain.dev/test.php.

Debugging Functions

The debugging functions allow you to pretty print variable values to the screen.

//** Debugging **//
if ( ! function_exists( 'wps_printr' ) ) {
/**
* Pretty prints variable (array) value.
* @author Travis Smith <[email protected]>
*
* @param $args Variable to be outputted.
* @param string $name Title to output before the variable output.
*/
function wps_printr( $args, $name = '' ) {
if ( apply_filters( 'wps_debug_off', false ) ) {
return;
}
if ( '' !== $name && false !== $name ) {
printf( '<strong>%s</strong><br/>', $name );
}
if ( is_array( $args ) ) {
printf( '<pre>%s</pre>', htmlspecialchars( print_r( $args, true ) ) );
} else {
var_dump( $args );
}
}
}
if ( function_exists( 'wps_printr' ) && ! function_exists( 'wps_die' ) ) {
/**
* Pretty prints variable (array) value & dies.
* @author Travis Smith <[email protected]>
*
* @param $args Variable to be outputted.
* @param string $name Title to output before the variable output.
*/
function wps_die( $args, $name = '' ) {
if ( apply_filters( 'wps_debug_off', false ) ) {
return;
}
wp_die( wps_printr( $args, $name ) );
}
}

Optionally Load the Admin Environment

All you need to do is uncomment the line with wps_load_admin().

//** Admin **//
/**
* Pluggable function, prevent redirect to admin pages
* @author Travis Smith <[email protected]>
*/
function auth_redirect() {
$loginusername = 'admin';
$user = get_user_by( 'login', $loginusername );
wp_set_current_user( $user->ID, $loginusername );
wp_set_auth_cookie( $user->ID );
}
/**
* Load the WordPress Admin Environment
* @author Travis Smith <[email protected]>
*/
function wps_load_admin() {
// Select either Network or User Admin
// define( 'WP_NETWORK_ADMIN', TRUE ); // Used in is_network_admin()
define( 'WP_USER_ADMIN', TRUE ); // Used in is_user_admin()
define( 'WP_BLOG_ADMIN', TRUE ); // Used in is_blog_admin()
define( 'WP_ADMIN', TRUE ); // Used in is_admin()
// Required for admin.php & prevent errors
global $wp_db_version, $_wp_submenu_nopriv;
require( './wp-admin/admin.php' );
echo '<h1>Admin Loaded</h1>';
}
// Load Admin
//wps_load_admin();

Optionally Load the User Functions

// User functions
//require( './wp-admin/includes/user.php' );

All you need to do is uncomment the line with require( './wp-admin/includes/user.php' );.

Optionally Load the Plugins API

// WordPress Plugins API
//require( './wp-admin/includes/plugin_install.php' );
// Endpoints
//https://api.wordpress.org/plugins/info/1.0/{slug}
//https://api.wordpress.org/plugins/info/1.0/{slug}.json
//https://api.wordpress.org/plugins/update-check/1.0/
//https://api.wordpress.org/plugins/update-check/1.1/
// Importers
//https://api.wordpress.org/core/importers/1.0/ (serialized)
//https://api.wordpress.org/core/importers/1.1/ (JSON)
//Checksum
//https://api.wordpress.org/core/checksums/1.0/?version={wp-version}&locale=en_US (JSON)

All you need to do is uncomment the line with require( './wp-admin/includes/plugin_install.php' );.

Full Code

<?php
// Set date, just in case
date_default_timezone_set( 'America/New_York' );
// Load the WordPress Environment
define( 'WP_DEBUG', TRUE ); // Set to FALSE to remove DEBUG MODE
require( './wp-load.php' );
// User functions
//require( './wp-admin/includes/user.php' );
//** Admin **//
/**
* Pluggable function, prevent redirect to admin pages
* @author Travis Smith <[email protected]>
*/
function auth_redirect() {
$loginusername = 'admin';
$user = get_user_by( 'login', $loginusername );
wp_set_current_user( $user->ID, $loginusername );
wp_set_auth_cookie( $user->ID );
}
/**
* Load the WordPress Admin Environment
* @author Travis Smith <[email protected]>
*/
function wps_load_admin() {
// Select either Network or User Admin
// define( 'WP_NETWORK_ADMIN', TRUE ); // Used in is_network_admin()
define( 'WP_USER_ADMIN', TRUE ); // Used in is_user_admin()
define( 'WP_BLOG_ADMIN', TRUE ); // Used in is_blog_admin()
define( 'WP_ADMIN', TRUE ); // Used in is_admin()
// Required for admin.php & prevent errors
global $wp_db_version, $_wp_submenu_nopriv;
require( './wp-admin/admin.php' );
echo '<h1>Admin Loaded</h1>';
}
// Load Admin
//wps_load_admin();
// WordPress Plugins API
//require( './wp-admin/includes/plugin_install.php' );
// Endpoints
//https://api.wordpress.org/plugins/info/1.0/{slug}
//https://api.wordpress.org/plugins/info/1.0/{slug}.json
//https://api.wordpress.org/plugins/update-check/1.0/
//https://api.wordpress.org/plugins/update-check/1.1/
// Importers
//https://api.wordpress.org/core/importers/1.0/ (serialized)
//https://api.wordpress.org/core/importers/1.1/ (JSON)
//Checksum
//https://api.wordpress.org/core/checksums/1.0/?version={wp-version}&locale=en_US (JSON)
//** Debugging **//
if ( ! function_exists( 'wps_printr' ) ) {
/**
* Pretty prints variable (array) value.
* @author Travis Smith <[email protected]>
*
* @param $args Variable to be outputted.
* @param string $name Title to output before the variable output.
*/
function wps_printr( $args, $name = '' ) {
if ( apply_filters( 'wps_debug_off', false ) ) {
return;
}
if ( '' !== $name && false !== $name ) {
printf( '<strong>%s</strong><br/>', $name );
}
if ( is_array( $args ) ) {
printf( '<pre>%s</pre>', htmlspecialchars( print_r( $args, true ) ) );
} else {
var_dump( $args );
}
}
}
if ( function_exists( 'wps_printr' ) && ! function_exists( 'wps_die' ) ) {
/**
* Pretty prints variable (array) value & dies.
* @author Travis Smith <[email protected]>
*
* @param $args Variable to be outputted.
* @param string $name Title to output before the variable output.
*/
function wps_die( $args, $name = '' ) {
if ( apply_filters( 'wps_debug_off', false ) ) {
return;
}
wp_die( wps_printr( $args, $name ) );
}
}
/**
* Plugins API Remote Post Example
*
* @author Travis Smith <[email protected]>
*/
function wps_plugins_api_remote_post() {
$args = (object) array( 'slug' => 'custom-favicon' );
$request = array( 'action' => 'plugin_information', 'timeout' => 15, 'request' => serialize( $args ) );
$url = 'http://api.wordpress.org/plugins/info/1.0/';
$response = wp_remote_post( $url, array( 'body' => $request ) );
$plugin_info = unserialize( $response['body'] );
wps_printr( $plugin_info, 'plugin_info' );
}
/**
* Helper function to output plugins_api()
*
* @author Travis Smith <[email protected]>
* @param $result array Array of plugins_api() result.
*/
function wps_output_result( $result ) {
/** Check for Errors & Display the results */
if ( is_wp_error( $result ) ) {
wps_printr( $result->get_error_message() );
} else {
wps_printr( $result );
}
}
/**
* Plugins API using plugins_api(): Get specific plugin information
*
* @author Travis Smith <[email protected]>
*/
function wps_plugins_api_plugin_information() {
$call_api = plugins_api( 'plugin_information', array( 'slug' => 'custom-favicon' ) );
wps_output_result( $call_api );
}
/**
* Plugins API using plugins_api(): Get plugins with tag
*
* @author Travis Smith <[email protected]>
*/
function wps_plugins_api_hot_tags() {
/** Prepare our query */
$call_api = plugins_api( 'hot_tags',
array(
'number' => '50',
)
);
wps_output_result( $call_api );
}
/**
* Plugins API using plugins_api(): Search plugins
*
* @author Travis Smith <[email protected]>
*/
function wps_plugins_api_query_plugins() {
$call_api = plugins_api( 'query_plugins',
array(
'browse' => 'top-rated',
'page' => '1',
'per_page' => '5',
'fields' => array(
'downloaded' => false,
'rating' => false,
'description' => false,
'short_description' => false,
'donate_link' => false,
'tags' => false,
'sections' => false,
'homepage' => false,
'added' => false,
'last_updated' => false,
'compatibility' => false,
'tested' => false,
'requires' => false,
'downloadlink' => true,
)
)
);
wps_output_result( $call_api );
}
// Execute plugins_api() functions
//wps_plugins_api_remote_post();
//wps_plugins_api_hot_tags();
//wps_plugins_api_query_plugins();
view raw test.php hosted with ❤ by GitHub

Written by Travis Smith · Categorized: Snippets

Feb 15 2014

Popular WordPress SQL Scripts: User Administration

Here are some of the most common WordPress SQL user administration scripts that I run.

Backup! Backup! Backup!

First and foremost, before manipulating the database, ALWAYS back it up!

I am going to assume that you have access via a WordPress SQL Plugin or phpMyAdmin.

Remember, if you are like me and change the prefix, be sure to change the wp_ prefixes below to whatever your prefix is. I have added myprefix_ to help demonstrate where this change would be.

Change Default Administrator Name

UPDATE wp_users SET user_login = 'NewName' WHERE user_login = 'Admin';
UPDATE myprefix_users SET user_login = 'NewName' WHERE user_login = 'Admin';
view raw default-admin-name.sql hosted with ❤ by GitHub

Reset User Password

UPDATE wp_users SET user_pass =md5('newpassword') WHERE user_login = 'yourusername');
UPDATE myprefix_users SET user_pass =md5('newpassword') WHERE user_login = 'yourusername');
view raw user-password.sql hosted with ❤ by GitHub

Delete Orphaned User Meta

DELETE FROM wp_usermeta WHERE user_id NOT IN (SELECT ID FROM wp_users)
DELETE FROM myprefix_usermeta WHERE user_id NOT IN (SELECT ID FROM myprefix_users)
view raw orphaned-wpusermeta.sql hosted with ❤ by GitHub

Replace User Meta

UPDATE wp_usermeta SET meta_key = REPLACE (meta_key, 'old_name', 'new_name');
UPDATE myprefix_usermeta SET meta_key = REPLACE (meta_key, 'old_name', 'new_name');
view raw replaceMetaKey.sql hosted with ❤ by GitHub

Add New Admin User

In the example below, I am using an ID of 2. Change this number to the next user available, or some safe high number.

INSERT INTO databasename.wp_users (ID, user_login, user_pass, user_nicename, user_email, user_url, user_registered, user_activation_key, user_status, display_name) VALUES ('2', 'admin_demo', MD5('demo_password'), 'Travis Smith', '[email protected]', 'http://wpsmith.net/', '2014-02-15 00:00:00', '', '0', 'Travis Smith');
INSERT INTO databasename.wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, '2', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO databasename.wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, '2', 'wp_user_level', '10');
INSERT INTO databasename.myprefix_users (ID, user_login, user_pass, user_nicename, user_email, user_url, user_registered, user_activation_key, user_status, display_name) VALUES ('2', 'admin_demo', MD5('demo_password'), 'Travis Smith', '[email protected]', 'http://wpsmith.net/', '2014-02-15 00:00:00', '', '0', 'Travis Smith');
INSERT INTO databasename.myprefix_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, '2', 'myprefix_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO databasename.myprefix_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, '2', 'myprefix_user_level', '10');
view raw new-admin.sql hosted with ❤ by GitHub

Delete Unknown Users

This will delete users not found in comments or as an author of a post. Do not use this script for community sites or sites with Subscribers.

DELETE FROM wp_users WHERE ID > 1 AND ID NOT IN (SELECT DISTINCT post_author FROM wp_posts) AND ID NOT IN (SELECT DISTINCT user_id FROM wp_comments);
DELETE FROM wp_usermeta WHERE user_id > 1 AND user_id NOT IN (SELECT DISTINCT post_author FROM wp_posts) AND user_id NOT IN (SELECT DISTINCT user_id FROM wp_comments);
DELETE FROM wp_links WHERE link_owner > 1 AND link_owner NOT IN (SELECT DISTINCT post_author FROM wp_posts) AND link_owner NOT IN (SELECT DISTINCT user_id FROM wp_comments);
DELETE FROM myprefix_users WHERE ID > 1 AND ID NOT IN (SELECT DISTINCT post_author FROM myprefix_posts) AND ID NOT IN (SELECT DISTINCT user_id FROM myprefix_comments);
DELETE FROM myprefix_usermeta WHERE user_id > 1 AND user_id NOT IN (SELECT DISTINCT post_author FROM myprefix_posts) AND user_id NOT IN (SELECT DISTINCT user_id FROM myprefix_comments);
DELETE FROM myprefix_links WHERE link_owner > 1 AND link_owner NOT IN (SELECT DISTINCT post_author FROM myprefix_posts) AND link_owner NOT IN (SELECT DISTINCT user_id FROM myprefix_comments);
view raw delete-unknown-users.sql hosted with ❤ by GitHub

Get All Admins

SELECT u.ID, u.user_login, u.user_nicename, u.user_email FROM wp_users u INNER JOIN wp_usermeta m ON m.user_id = u.ID WHERE m.meta_key = 'wp_capabilities' AND m.meta_value LIKE '%admin%' ORDER BY u.user_registered
SELECT u.ID, u.user_login, u.user_nicename, u.user_email FROM myprefix_users u INNER JOIN myprefix_usermeta m ON m.user_id = u.ID WHERE m.meta_key = 'myprefix_capabilities' AND m.meta_value LIKE '%admin%' ORDER BY u.user_registered
view raw get-admins.sql hosted with ❤ by GitHub

Written by Travis Smith · Categorized: Snippets

  • Twitter
  • Facebook
  • LinkedIn
  • Google+
  • RSS

Copyright © 2025 � WP Smith on Genesis on Genesis Framework � WordPress � Log in