问题描述

我想将”Company Name” 字段添加到管理面板中的添加新用户页面。我做了相当多的搜索,并且无法找到有关如何做到这一点的细节。我可以轻松地添加信息到个人资料页面和注册..

   function my_custom_userfields( $contactmethods ) {
    //Adds customer contact details
    $contactmethods['company_name'] = 'Company Name';
    return $contactmethods;
   }
   add_filter('user_contactmethods','my_custom_userfields',10,1);

但没有任何骰子。

最佳解决方案

我有同样的需要,并创建了以下 hack:

<?php
function hack_add_custom_user_profile_fields(){
    global $pagenow;

    # do this only in page user-new.php
    if($pagenow !== 'user-new.php')
        return;

    # do this only if you can
    if(!current_user_can('manage_options'))
        return false;

?>
<table id="table_my_custom_field" style="display:none;">
<!-- My Custom Code { -->
    <tr>
        <th><label for="my_custom_field">My Custom Field</label></th>
        <td><input type="text" name="my_custom_field" id="my_custom_field" /></td>
    </tr>
<!-- } -->
</table>
<script>
jQuery(function($){
    //Move my HTML code below user's role
    $('#table_my_custom_field tr').insertAfter($('#role').parentsUntil('tr').parent());
});
</script>
<?php
}
add_action('admin_footer_text', 'hack_add_custom_user_profile_fields');


function save_custom_user_profile_fields($user_id){
    # again do this only if you can
    if(!current_user_can('manage_options'))
        return false;

    # save my custom field
    update_usermeta($user_id, 'my_custom_field', $_POST['my_custom_field']);
}
add_action('user_register', 'save_custom_user_profile_fields');

次佳解决方案

user_new_form 是可以在这里做魔术的钩子。

function custom_user_profile_fields($user){
    ?>
    <h3>Extra profile information</h3>
    <table class="form-table">
        <tr>
            <th><label for="company">Company Name</label></th>
            <td>
                <input type="text" class="regular-text" name="company" value="<?php echo esc_attr( get_the_author_meta( 'company', $user->ID ) ); ?>" id="company" /><br />
                <span class="description">Where are you?</span>
            </td>
        </tr>
    </table>
<?php
}
add_action( 'show_user_profile', 'custom_user_profile_fields' );
add_action( 'edit_user_profile', 'custom_user_profile_fields' );
add_action( "user_new_form", "custom_user_profile_fields" );

function save_custom_user_profile_fields($user_id){
    # again do this only if you can
    if(!current_user_can('manage_options'))
        return false;

    # save my custom field
    update_usermeta($user_id, 'company', $_POST['company']);
}
add_action('user_register', 'save_custom_user_profile_fields');

有关更多详情,请访问我的博客:http://scriptbaker.com/adding-custom-fields-to-wordpress-user-profile-and-add-new-user-page/

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。