前几天有人问悟空搜,怎么在我的个人资料这个页面添加其他的字段呢?例如:QQ号码、微信号码之类的input表单输入框。
WordPress默认的设置里是没有QQ号码、微信号码的,如果要添加我们只能使用代码添加自定义字段。有很多插件可以实现这个功能,但是能不用插件就不用插件。今天悟空搜分享一篇免插件纯代码实现个人资料添加自定义字段的WordPress教程。
添加用户自定义字段
首先我们在我的个人资料编辑页面添加一行“微信号码”的自定义字段。
直接把下面的代码复制到主题的functions.php文件中,即可在用户资料编辑页面看到一个“微信号码”的表单项。
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, 'wx_username', $_POST['wx_username'] );
}
function wizhi_extra_user_profile_fields( $user ) { ?>
<h3>附加用户字段</h3>
<table class="form-table">
<tr>
<th><label for="wx_username">微博用户名</label></th>
<td>
<input type="text" id="wx_username" name="wx_username" size="20" value="<?php echo esc_attr( get_the_author_meta( 'wx_username', $user->ID ) ); ?>">
<span class="description">请输入微博用户名。</span>
</td>
</tr>
</table>
<?php }
代码说明与修正:
- 代码中使用了
wx_username作为用户元数据的键名,但描述是“微博用户名”,与文章开头提到的“微信号码”不符。请根据实际需要修改字段标签和说明。 - 在
wizhi_extra_user_profile_fields函数中,获取用户元数据时使用的键名应为'wx_username',与保存时保持一致。原文代码中误写为'wx_user_name',已在上方代码中修正。 - 此代码会在用户个人资料页面(用户自己查看)和编辑用户页面(管理员编辑)都添加字段。
- 保存函数
wizhi_save_extra_user_profile_fields中直接使用了$_POST['wx_username'],在实际生产环境中,建议添加非空验证和安全性过滤(如sanitize_text_field)。
调用自定义字段
添加好用户自定义字段后,如何获取使用这个字段呢?获取的方法也很简单,示例代码如下:
<?php
$current_user = wp_get_current_user();
echo get_user_meta( $current_user->ID, 'wx_username', true );
?>
代码说明与修正:
get_user_meta函数用于获取用户元数据。第三个参数设为true表示返回单个值(字符串)。- 原示例代码只是获取了值但没有输出,通常需要配合
echo来显示。上方代码已添加echo。 - 把上面的调用自定义字段的代码添加到想要显示用户字段内容的页面模板中即可(例如 single.php、author.php 或自定义的用户中心页面)。
扩展:获取任意用户的自定义字段
如果你想在文章页面显示作者的自定义字段,可以使用以下代码:
<?php
$author_id = get_the_author_meta( 'ID' );
$weixin = get_user_meta( $author_id, 'wx_username', true );
if ( ! empty( $weixin ) ) {
echo '作者微信号:' . esc_html( $weixin );
}
?>