WordPress个人资料添加自定义字段input表单

前几天有人问悟空搜,怎么在我的个人资料这个页面添加其他的字段呢?例如:QQ号码、微信号码之类的input表单输入框。

WordPress默认的设置里是没有QQ号码、微信号码的,如果要添加我们只能使用代码添加自定义字段,有很多插件可以实现这个功能,但是能不用插件就不用插件嘛,今天悟空搜分享一篇免插件纯代码实现个人资料添加自定义字段的WordPress教程。

添加用户自定义字段

首先我们在我的个人资料编辑页面添加一行“微信号码”的自定义字段。

直接把下面的代码复制到主题的functions.php文件中,即可在用户资料编辑页面看到一个“QQ号码”的表单项。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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_user_name', $user->ID )); ?>">
            <span class="description">请输入微博用户名。</span>
        </td>
    </tr>
</table>
<?php }?>

调用自定义字段

添加好用户自定义字段后,如何获取使用这个字段呢?获取的方法也很简单,示例代码如下:


1
2
3
4
<?php
$current_user = wp_get_current_user();
get_user_meta( $current_user->ID, 'wx_username', true);
?>

把上面的调用自定义字段添加到想要显示用户字段内容的页面即可。

扫码关注wp悟空搜

精选优质免费WordPress主题模板,分享最新WordPress实用建站教程!

记住我们的网址:ztJun.com

原文链接:https://xiaohost.com/1294.html,转载请注明出处。
0