问题前言
有时候需要给用户新增一个字段来存储某些信息,那么怎么来添加自定义字段呢?
下面我将简单说一下如何删除、添加和调用自定义用户信息字段。
解决方案
添加或删除字段,可以在主题的 functions.php 文件添加下面的代码:
/** * 自定义用户个人资料信息 * https://kuloucun.com/123.html */ add_filter( 'user_contactmethods','wpdaxue_add_contact_fields' ); function wpdaxue_add_contact_fields( $contactmethods ) { $contactmethods['qq_weibo'] = '腾讯微博'; // 增加字段:qq_weibo $contactmethods['sina_weibo'] = '新浪微博'; $contactmethods['twitter'] = 'Twitter'; unset( $contactmethods['yim'] ); // 删除字段:yim unset( $contactmethods['aim'] ); unset( $contactmethods['jabber'] ); return $contactmethods; }
以上代码通过 user_contactmethods 这个钩子添加了3个自定义字段,同时移除了字段 yim、aim、jabber,用法一目了然,就不多说
如何调用上面的字段
使用 the_author_meta() 或 get_the_author_meta() 这两个函数即可。
the_author_meta() 直接打印输出字段值
get_the_author_meta() 返回字段值给其他函数调用
注:在没有指定用户ID等明确信息时,以上两个函数只能在循环(Loop)内才能正常使用。
例:比如我们要调用 腾讯微博”qq_weibo”字段,可以使用使用下面的代码:
//打印输出"qq_weibo"字段的值(直接输出) the_author_meta( 'qq_weibo' ); //直接输出"qq_weibo"字段的值 echo get_the_author_meta( 'qq_weibo' );
注:我们在实际使用的时候,最好先通过 IF 语句判断用户是否填写了腾讯微博这个字段(即判断”qq_weibo”字段是否存在值),如果填写了,就输出,否者不输出
if ( get_the_author_meta( 'qq_weibo' ) ){ echo '腾讯微博:'.get_the_author_meta( 'qq_weibo' ); }
使用说明
请根据自己实际情况做相应修改