0

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?

1 Answer 1

3

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.

<?php
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:

<?php
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

2
  • 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
    Commented Sep 4, 2011 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. Commented Sep 4, 2011 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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