Save user-specific options in WordPress admin

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

Leave a Comment