Best practice for show data to one specific user?

To check if an user is a specific user you have 4 options:

  • check the ‘ID’
  • check the nicename (slug)
  • check the email
  • check the user login

All these 4 fields are unique for every user.

So, check the ID is an option, but is the worst: when create that user admin doesn’t know the id, he had look at the ID after he had created user, so you can write your code after the user is created… this is bad.

The other 3 options are a bit (just a bit) better: you can wite the code before the user is created, E.G.:

if ( 'standard_user' === $current_user->user_nicename ) {
  // do something
}

And after that, the admin have to create the user, but remembering to use 'standard_user' as user nicename.

However, once you ask about best practice, I can’t say it’s a best practice, because it needs an hardcoding: you write in code something that to work needs the admin when create user type a specific string… and if a typo happen? if admin doesn’t recall exactly which is the string to use?

If you are writing the code for yourself, this can be used with no much pain, but if you are writing this for someone else (a customer?) or you plan to distribuite your code, you should surely do it in another way.

There are different possibilities, this is one:

First of all, you have to think which is the role normally you have added to that particular standard user.

Assuming that user should be a contributor.

On plugin activation create a custom role cloning contributor capabilities.

function myplugin_install() {
  $contributor = get_role('contributor');
  $standard = add_role( 'standard', 'Standard User', $contributor->capabilities );
}

register_activation_hook( __FILE__, 'myplugin_install' );

After that, write your condiction like this:

$user = wp_get_current_user();

if ( user_can($user, 'manage_options') ) {
  // code for admin
} elseif ( in_array( 'standard', $user->roles ) ) {
  // code for your standard user 
} else {
  // code for others
}

Now, when the administrator create the Standard user have only to choose ‘Standard User’ from the user role dropdown.

PS: remember to remove your custom role on plugin deactivation:

function myplugin_unistall() {
  remove_role( 'standard' );
}

register_deactivation_hook( __FILE__, 'myplugin_unistall' );