User fields that can be edited by administrator?

How can I add custom user fields for a user profile that an administrator can edit? I want the user to be able to see the value of the field on their profile, but I don’t want them to edit it. How can I achieve this with WordPress?

Related posts

Leave a Reply

1 comment

  1. I used this so a teacher would mark what courses the students were subscribed to.

    This is a generic version of that code, using only one extra field.

    Admin view

    profile admin view


    Other users view

    profile user view


    <?php
    /* Plugin Name: Admin User Fields */
    
    add_action( 'admin_init', 'wpse_70265_init');
    
    function wpse_70265_init() 
    {
        if( current_user_can( 'administrator' ) ) 
        {
            add_action( 'show_user_profile', 'wpse_70265_profile_fields', 10 );
            add_action( 'edit_user_profile', 'wpse_70265_profile_fields', 10 );
        } 
        else 
        {
            add_action( 'show_user_profile', 'wpse_70265_non_edit_profile_fields', 10 );    
        }
        
        add_action( 'personal_options_update', 'wpse_70265_save_profile_fields' );
        add_action( 'edit_user_profile_update', 'wpse_70265_save_profile_fields' );
    }
    
    function wpse_70265_non_edit_profile_fields( $user ) 
    { 
        $has_option = get_the_author_meta( 'option_status', $user->ID );
        ?> 
        <table class="form-table">
            <tr>
                <th><label for="agree">Option Status</label></th>
                <td>
                    <ul>
                        <li><?php if ( 'yes' == $has_option ) { echo "checked"; } else { echo "not checked"; }?></li>
                    </ul>
                </td>           
            </tr>
            
        </table>
        <?php 
    }
    
    function wpse_70265_profile_fields( $user ) 
    { 
        $has_option = get_the_author_meta( 'option_status', $user->ID );
        ?>
    
        <table class="form-table">
            <tr>
                <th><label for="agree">Option Status</label></th>
                <td>
                    <ul>
                        <li><input value="yes" name="option_status" <?php if ( 'yes' == $has_option ) { ?>checked="checked"<?php }?> type="checkbox" /> Enable/Disable</li>
                    </ul>
                </td>           
            </tr>
            
        </table>
        <?php 
    }
    
    function wpse_70265_save_profile_fields( $user_id ) 
    {
    
        if ( !current_user_can( 'edit_user', $user_id ) )
            return false;
    
        update_usermeta( $user_id, 'option_status', $_POST['option_status'] );
    }