+ 收藏我们

网站模板

网站模板搜索
404模板 营销型模板 外贸网站模板 单页模板 双语模板 标签大全
电话:18630701785
首页 > 站长学院 > 添加用户字段(user_meta)到用户资料编辑页面并获取 >

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

时间:2024-08-02 11:54:27

在进行WordPress功能开发的时候,我们经常需要一些附加的自定义字段来实现我们的需求,用户自定义字段也是WordPress中自定义字段的一种。有很多插件可以实现文章自定义字段的添加,比如本站中介绍过的Piklist插件。而支持创建用户自定义字段的插件却不多,即使有,也做得没有添加文章自定义字段那样方便。可能是因为添加用户自定义字段的需求比较少的缘故吧。今天我们来看一下怎么通过代码添加用户自定义字段。

通过代码添加用户自定义字段
在下面的实例代码中,我们将为用户资料编辑页面添加一个允许用户输入“微博用户名” 的自定义字段。直接把下面的代码复制到主题的functions.php或插件的功能代码中,即可在用户资料编辑页面看到一个“微博用户名”的表单项,该表单项的值将被作为用户自定义字段保存到WordPress 数据库的 wp_user_meta 数据表中。

复制
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函数。直接使用该函数即可获取我们添加的用户自定义字段。示例代码如下:

复制
$current_user = wp_get_current_user();
get_user_meta( $current_user->ID, 'weibo_username', true); 

有问题可以加入网站技术QQ群一起交流学习

本站会员学习、解决问题QQ群(691961965)

客服微信号:lpf010888

pbootcms教程

织梦教程

站长学院

SEO

wordpress

竞价教程

信息流

Title