WordPress 用户配置文件屏幕允许您设置社交服务的值,但一些默认服务是不相关的,即 AIM 和 Yahoo!我是;再加上缺少 Twitter 和 Facebook 字段这一事实。您很快意识到默认表单……需要工作。 WordPress 提供了一种添加和删除配置文件字段的方法。让我向您展示它是如何工作的!
过滤器设置
第一步是在您的 functions.php 文件中创建一个函数,它将接受配置文件键和值的数组:
function modify_contact_methods($profile_fields) { // Field addition and removal will be done here } add_filter('user_contactmethods', 'modify_contact_methods');
此函数提供对重要的受保护数组的访问。返回值成为用户配置文件字段列表。
添加配置文件字段
添加一个新字段,例如 Twitter 句柄,包括向传入的数组添加一个键,其中一个值将充当字段标签:
function modify_contact_methods($profile_fields) { // Add new fields $profile_fields['twitter'] = 'Twitter Username'; $profile_fields['facebook'] = 'Facebook URL'; $profile_fields['gplus'] = 'Google+ URL'; return $profile_fields; } add_filter('user_contactmethods', 'modify_contact_methods');
只需将该键/值添加到数组中即可为表单添加一个新字段。
删除配置文件字段
相反,从所述数组中删除一个键会从用户配置文件表单中删除一个字段:
function modify_contact_methods($profile_fields) { // Add new fields $profile_fields['twitter'] = 'Twitter Username'; $profile_fields['facebook'] = 'Facebook URL'; $profile_fields['gplus'] = 'Google+ URL'; // Remove old fields unset($profile_fields['aim']); return $profile_fields; } add_filter('user_contactmethods', 'modify_contact_methods');
上面的代码从编辑配置文件表单中删除了 AIM 字段。
检索自定义字段值
要检索自定义字段值,请使用 get_the_author_meta 方法:
// Retrieve a custom field value $twitterHandle = get_the_author_meta('twitter');
轻松添加个人资料表单字段的能力很棒;超级简单,无需插件!