Reputation: 59
I am trying to add custom css for admin as below
add_action('admin_head', 'hey_custom_admin_css');
function hey_custom_admin_css() {
global $current_user;
$user_id = get_current_user_id();
if(is_admin() && $user_id != '1'){
echo "<style>#wpwrap{background-color:red;}</style>";
}
}
and working perfectly but I want to use it for username, not for user ID
Is it possible to have? If yes then please give me suggestions
Thanks
Edited code
1st... Css Working but for all users. Including which are listed in code.
<?php
/**
* Plugin Name: My Plugin
* Plugin URI: https://google.com
* Description: Me
* Version: 1.0
* Author: Plugin
* Author URI: https://google.com
*/
add_action('admin_head', 'hey_custom_admin_css');
function hey_custom_admin_css() {
global $current_user;
wp_get_current_user();
$username = $current_user->user_login;
if(is_admin() && ($username != 'xyz' || $username != 'abc')){
echo "
<style>
#wpwrap{background-color:red;}
</style>";
} }
Second... Giving error
<?php
/**
* Plugin Name: My Plugin
* Plugin URI: https://google.com
* Description: Me
* Version: 1.0
* Author: Plugin
* Author URI: https://google.com
*/
global $current_user;
wp_get_current_user(); //Error on this line
$username = $current_user->user_login;
if(is_admin() && ($username != 'xyz' || $username != 'abc')){
echo "
<style>
#wpwrap{background-color:red;}
</style>";
}
Given error for second
Fatal error: Uncaught Error: Call to undefined function wp_get_current_user() in /home/dh_w4i633/site.com/wp-content/plugins/me/me.php:13 Stack trace: #0 /home/dh_w4i633/site.com/wp-settings.php(371): include_once() #1 /home/dh_w4i633/site.com/wp-config.php(106): require_once('/home/dh_w4i633...') #2 /home/dh_w4i633/site.com/wp-load.php(37): require_once('/home/dh_w4i633...') #3 /home/dh_w4i633/site.com/wp-admin/admin.php(34): require_once('/home/dh_w4i633...') #4 /home/dh_w4i633/site.com/wp-admin/plugins.php(10): require_once('/home/dh_w4i633...') #5 {main} thrown in /home/dh_w4i633/site.com/wp-content/plugins/me/me.php on line 13
Upvotes: 2
Views: 638
Reputation: 555
<?php
global $current_user;
wp_get_current_user();
$username = $current_user->user_login;
if(is_admin() && ($username == 'username' || $username == 'another_username')){
echo "<style>#wpwrap{background-color:red;}</style>";
}
?>
Edit:
The second code in your edit is giving you an error since you're running it at all times instead of attaching it to a hook, hence the error.
Your first code in your edit seems to be correct, so let us stick with that. The reason it is changing the css for all users including your unwanted users is because of the OR ||
operator. You'll want to replace it with the AND &&
operator. Your condition will become:
if(is_admin() && $username != 'xyz' && $username != 'abc')
Upvotes: 2