WordPress - 保存自定义用户个人资料字段

6

我目前正在尝试为我的WordPress用户添加一些自定义用户资料字段。

我已将以下代码添加到我的functions.php文件中,但由于某种原因,输入的数据没有保存...

//** CUSTOM USER META **//

add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );

function my_show_extra_profile_fields( $user ) { ?>
    <h3>Extra profile information</h3>
    <table class="form-table">
        <tr>
            <th><label for="club">Club You Support</label></th>
            <td>
                <input type="text" name="club" id="club" value="<?php echo esc_attr( get_the_author_meta( 'club', $user->ID ) ); ?>" class="regular-text" /><br />
            </td>
        </tr>
    </table>
<?php }

   add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
   add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );

   function my_save_extra_profile_fields( $user_id ) {
       update_usermeta( $user_id, 'club', sanitize_text_field( $_POST['club']) );
   } 

有什么想法为什么这个数据无法保留吗?

1
我复制粘贴了这段代码,它完美地为我工作了。我的add_action看起来像这样add_action( 'hook', 'function_name', 10, 1 );,但我不认为这会有任何影响。 - Pine
好奇怪!可能是因为我在一个暂存域上使用它吗?也许它无法访问真实网站的数据库 :/ - Phil Nind
我直接将这个代码段放入我的functions.php文件中,它也对我起作用了。你的安装中可能有其他插件正在接管该操作吗? - Dylan Hildenbrand
1个回答

2

在WordPress中创建新的个人资料字段有一种更简单和适当的方法。基于您上面的代码,尝试将下面的代码放置在您主题的functions.php文件中:

function my_show_extra_profile_fields {
    $user_contact_method['club'] = 'Club You Support';
    return $user_contact_method;
}
add_filter( 'user_contactmethods', 'my_show_extra_profile_fields' );

这将自动在您的个人资料页面上创建新字段,并将它们作为用户的自定义字段(meta)保存到数据库中。
您可以使用 the_author_meta('club'); 在您的主题上显示这些信息。

你可以通过在同一个函数内创建新的 $user_contact_method 来添加其他字段。例如:$user_contact_method['a'] = '另一个选项';$user_contact_method['b'] = '再来一个选项';等等。 - Gus Fune

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接