在進行WordPress功能開發(fā)的時候,我們經(jīng)常需要一些附加的自定義字段來實現(xiàn)我們的需求,用戶自定義字段也是WordPress中自定義字段的一種。有很多插件可以實現(xiàn)文章自定義字段的添加,比如本站中介紹過的Piklist插件。而支持創(chuàng)建用戶自定義字段的插件卻不多,即使有,也做得沒有添加文章自定義字段那樣方便??赡苁且驗樘砑佑脩糇远x字段的需求比較少的緣故吧。今天我們來看一下怎么通過代碼添加用戶自定義字段。
通過代碼添加用戶自定義字段
在下面的實例代碼中,我們將為用戶資料編輯頁面添加一個允許用戶輸入“微博用戶名” 的自定義字段。直接把下面的代碼復制到主題的functions.php或插件的功能代碼中,即可在用戶資料編輯頁面看到一個“微博用戶名”的表單項,該表單項的值將被作為用戶自定義字段保存到WordPress 數(shù)據(jù)庫的 wp_user_meta 數(shù)據(jù)表中。
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函數(shù)。直接使用該函數(shù)即可獲取我們添加的用戶自定義字段。示例代碼如下:
$current_user = wp_get_current_user();
get_user_meta( $current_user->ID, 'weibo_username', true);
- 首先使用 wp_get_current_user 函數(shù)獲取用戶對象
- 然后使用 get_user_meta 獲取當前用戶的自定義字段信息


