将自定义字段添加到现有节中的用户编辑页


Adding a custom field to the user edit page within an existing section

我正试图在WordPress上的user-edit.php页面中添加一个额外的字段。

我想把它添加到"传记信息"字段上方的"关于这个用户/你"部分。我已经编辑了文件以添加另一个,但由于某种原因,它不会保存我输入的信息。

<table class="form-table">
<tr class="user-job-title-wrap">
    <th><label for="job_title"><?php _e('Job Title'); ?></label></th>
    <td><input type="text" name="job_title" id="job_title" value="<?php echo esc_attr( $profileuser->job_title ) ?>" class="regular-text ltr" />
</td>
</tr>
<tr class="user-description-wrap">
    <th><label for="description"><?php _e('Biographical Info'); ?></label></th>
    <td><textarea name="description" id="description" rows="5" cols="30"><?php echo $profileuser->description; // textarea_escaped ?></textarea>
    <p class="description"><?php _e('Share a little biographical information to fill out your profile. This may be shown publicly.'); ?></p></td>
</tr>
...

它确实向wp_usermeta数据库添加了正确的meta_key,但meta_value保持为空。如果我在数据库中手动输入meta_value并重新加载用户编辑页面,则该值将正确加载到输入字段中,但对该字段所做的任何更改都不会记录到数据库中。

以下是添加字段和保存更新字段数据的wordpress挂钩:

// ADDING CUSTOM FIELDS TO INDIVIDUAL USER SETTINGS PAGE AND TO USER LIST
add_action( 'show_user_profile', 'add_extra_user_fields' );
add_action( 'edit_user_profile', 'add_extra_user_fields' );
function add_extra_user_fields( $user )
{
    ?>
        <h3><?php _e("My TITLE", "my_theme_domain"); ?></h3>
        <table class="form-table">
            <tr class="user-job-title-wrap">
                <th><label for="job_title"><?php _e('Job Title'); ?></label></th>
                <td><input type="text" name="job_title" id="job_title" value="<?php echo esc_attr( $profileuser->job_title ) ?>" class="regular-text ltr" />
            </td>
            </tr>
            <tr class="user-description-wrap">
                <th><label for="description"><?php _e('Biographical Info'); ?></label></th>
                <td><textarea name="description" id="description" rows="5" cols="30"><?php echo $profileuser->description; // textarea_escaped ?></textarea>
                <p class="description"><?php _e('Share a little biographical information to fill out your profile. This may be shown publicly.'); ?></p></td>
            </tr>
        </table>
    <?php
}

--(更新)--您只能使用下面的save_extra_user_fields来解决您的问题(…保存信息…),如果您愿意,还可以保留您的代码。

// Saving Updated fields data
add_action( 'personal_options_update', 'save_extra_user_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_fields' );
function save_extra_user_fields( $user_id )
{
    update_user_meta( $user_id, 'job_title', sanitize_text_field( $_POST['job_title'] ) );
    update_user_meta( $user_id, 'description', sanitize_text_field( $_POST['description'] ) );
}

此代码位于活动子主题或主题的function.php文件上…

使用php:使用自定义用户字段数据

  • 返回数据:get_the_author_meta( 'your_field_slug', $userID );
  • 显示数据(回显数据):the_author_meta( 'your_field_slug', $userID );