User fields that can be edited by administrator?

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'] );
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)