How to Save Different Usermeta Fields According to User Role?

Observation: following the guidelines suggested in this article, I’m trying to improve the quality both of the Q and the A. It’s a learning process…

In your original code, you were displaying different input fields according to the user role and other conditionals.

add_action( 'show_user_profile', 'user_fields_for_admin', 10);
add_action( 'edit_user_profile', 'user_fields_for_admin', 10);
function user_fields_for_admin( $user ){ 
    switch ($user->roles[0]) {
        case 'pending':
            if ($selected_register == "Owner"){
                // Display some fields;
            } elseif ($selected_register == "Board") {
                // Display other fields
            }
            break;

        case 'owner':
            // Display yet another fields
            break;
    }
}

But when saving the fields using update_usermeta (as per the code in your edited question), all the fields were being saved, regardless if they were being displayed or not.

You have to check if the field value is being passed, so the usermeta will not be overridden with non-existent values at each and every update.

function save_user_fields($user_id) {
    if (!current_user_can('edit_user', $user_id))
        return false;
    if( isset($_POST['unit_type']) )     update_usermeta($user_id, 'unit_type', $_POST['unit_type']);
    if( isset($_POST['registered_as']) ) update_usermeta($user_id, 'registered_as', $_POST['registered_as']);
    // ETC
}

Suggestions for debug and printing Html

For your reference, you can check the contents of a PHP object using this code:

echo '<pre>'.print_r($user, true).'</pre>';

And instead of echoing one line at the time, you can use the Heredoc sintax for easy reading/printing Html. PHP variables goes inside curly brackets. Example:

echo <<<HTML
    <h3>Owner Details</h3>
    <table class="form-table"><tbody><tr>
    <tr><th>First Name</th>
    <td><input type="text" name="first_name" id="first_name1" value="{$first_name}" class="regular-text" /></td>
    </tr>
    <tr><th>Last Name</th>
    <td><input type="text" name="last_name" id="last_name1" value="{$last_name}" class="regular-text" /></td>
    </tr>
HTML;

Leave a Comment