WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm writing a plugin that need to save user specific option in an admin page. I'm only thinking of adding username-prefix to option, for example:

$options = get_option('username-plugin_options');

Is there any better way doing that?

share|improve this question

When you register your setting (assuming you're using the settings API), you can get the current user object with wp_get_current_user. It returns a user object, and the property you'll want to use in your setting is user_nicename -- think of it like the user slug.

add_action( 'admin_init', 'wpse27690_register_setting' );
function wpse27690_register_setting()
    $user = wp_get_current_user();
    register_setting( $user->user_nicename . '_plugin_options', $user->user_nicename . '_plugin_options', 'wpse27690_sanitize' );

function wpse27690_sanitize( $in )
    // clean stuff here.
    return $in; 

You can do the same thing when retrieving the option. This is probably not a good idea, as Rarst points out in the comments. And it probably won't work with "subscriber" level users or those who can't manage options.

But if it's one or two options, the easiest thing to do would be to add fields to the user profile page. Not sure if that's what you want, but you can do it like this:

add_action( 'show_user_profile', 'wpse27690_user_form' ); // for you profile
add_action( 'edit_user_profile', 'wpse27690_user_form' ); // for other's profiles
function wpse27690_user_form( $user )
    // put your form fields here, probably a nonce or something

add_action( 'personal_options_update', 'wpse27690_user_save' ); // you profile
add_action( 'edit_user_profile_update', 'wpse27690_user_save' ); // other's profiles
function wpse27690_user_save( $user_id )
    // check nonces, permssions first

    // then save    
    if( isset( $_POST['_your_fields_name'] ) )
        update_user_meta( $user_id, 'wpse27690_user_key', esc_attr( $_POST['_your_fields_name'] ) );

When you save individual user options, it's going to be with update_user_meta

share|improve this answer
I am not sure using Settings API in this way is good idea. As far I know core code sticks with user meta for such things. – Rarst Sep 4 '11 at 16:30
I don't think it is either. I tested my first solution with a "subscriber" level user, and it didn't work. Subscribers can't use the options.php handler for the forms, got the "Cheatin' uh?" message. Answer changed to reflect that. – chrisguitarguy Sep 4 '11 at 16:35

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.