添加用户字段(user_meta)到用户资料编辑页面并获取

文 / @UTHEME

小本本的WordPress开发笔记

如果你正在进行WordPress功能开发,那么你肯定需要使用一些自定义字段来满足你的需求,其中包括用户自定义字段。虽然一些插件可以帮助你添加文章自定义字段,比如之前我们介绍过的Piklist插件,但支持创建用户自定义字段的插件相对较少。于是,如果你需要添加用户自定义字段的话,你可能只能通过代码来实现这一点。

通过代码添加用户自定义字段

下面的代码实例可以帮助你添加一个允许用户输入“微博用户名”的自定义字段。

add_action('show_user_profile','wizhi_extra_user_profile_fields');
add_action('edit_user_profile','wizhi_extra_user_profile_fields');
add_action('personal_options_update','wizhi_save_extra_user_profile_fields');
add_action('edit_user_profile_update','wizhi_save_extra_user_profile_fields');

function wizhi_save_extra_user_profile_fields($user_id) {
    if (!current_user_can('edit_user',$user_id)) {
        return false;
    }
    update_user_meta($user_id,'weibo_username',$_POST['weibo_username']);
}

function wizhi_extra_user_profile_fields($user) {?>
    <h3>附加用户字段</h3>
    <table class="form-table">
    <tr>
    <th><label for="weibo_username">微博用户名</label></th>
    <td>
    <input type="text" id="weibo_username" name="weibo_username" size="20" value="<?php echo esc_attr(get_the_author_meta('weibo_user_name',$user->ID));?>">
    <span class="description">请输入微博用户名。</span>
    </td>
    </tr>
    </table>
    <?php }?>

获取添加的用户自定义字段

添加完用户自定义字段后,你可以通过WordPress提供的get_user_meta函数来获取所添加的字段。示例代码如下:

<?php
$current_user = wp_get_current_user();
get_user_meta($current_user->ID,'weibo_username',true);
?>

 

添加UTHEME为好友
扫码添加UTHEME微信为好友
· 分享WordPress相关技术文章,主题上新与优惠动态早知道。
· 微信端最大WordPress社群,限时免费入群。