WordPress自定义Avatars头像功能实现方法


文章目录 隐藏

在某些情况下,为了增强用户体验,我们可能需要在网站上添加自定义头像上传功能,而不是依赖于Gravatar。以下代码展示了如何在WordPress网站上添加自定义头像功能,该功能包括在用户资料页面添加自定义头像字段,并通过过滤器显示自定义头像。

功能需求说明

以下代码示例展示了如何在WordPress主题的 functions.php 文件中添加自定义头像功能。具体实现包括在用户资料页面添加自定义头像字段,并通过过滤器显示自定义头像。

一、在用户资料页面添加自定义Avatar字段

function be_custom_avatar_field($user) { ?>
  <h2>自定义头像</h2>
  <table class="form-table" role="presentation">
    <tbody>
    <tr class="be_custom_avatar">
      <th><label for="be_custom_avatar">头像图片链接: </label></th>
      <td>
        <input type="text" name="be_custom_avatar" id="be_custom_avatar" class="regular-text ltr" value="<?php echo esc_url_raw(get_the_author_meta('be_custom_avatar', $user->ID)); ?>" />
        <p class="description" id="be_custom_avatar-description">输入头像的图片链接,图片尺寸 70x70 像素。</p>
      </td>
    </tr>
    </tbody>
  </table>
<?php }

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

function be_save_custom_avatar_field($user_id) {
  if (current_user_can('edit_user', $user_id)) {
    update_user_meta($user_id, 'be_custom_avatar', esc_url_raw($_POST['be_custom_avatar']));
  }
}

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

二、通过 add_filter 过滤器显示自定义头像

function be_gravatar_filter($avatar, $id_or_email, $size, $default, $alt) {
  // 获取用户的电子邮件地址
  $email = is_object($id_or_email) ? $id_or_email->comment_author_email : $id_or_email;
  
  // 如果电子邮件地址有效并且不存在于网站用户中,则返回默认头像
  if(is_email($email) && !email_exists($email)) {
    return $avatar;
  }
  
  // 获取用户自定义头像
  $user = get_user_by('email', $email);
  $custom_avatar = $user ? get_the_author_meta('be_custom_avatar', $user->ID) : '';
  
  // 显示自定义头像或默认头像
  if ($custom_avatar) {
    $return = '<img src="'.$custom_avatar.'" width="'.$size.'" height="'.$size.'" alt="'.$alt.'" />';
  } elseif ($avatar) {
    $return = $avatar;
  } else {
    $return = '<img src="'.$default.'" width="'.$size.'" height="'.$size.'" alt="'.$alt.'" />';
  }
  
  return $return;
}

add_filter('get_avatar', 'be_gravatar_filter', 10, 5);

代码解析

  1. 在用户资料页面添加自定义头像字段

    • 使用 show_user_profileedit_user_profile 钩子,在用户资料编辑页面添加一个输入字段,用于输入自定义头像的URL。

    • 使用 personal_options_updateedit_user_profile_update 钩子,在保存用户资料时保存自定义头像URL。

  2. 通过 add_filter 过滤器显示自定义头像

    • 使用 get_avatar 过滤器,根据用户的电子邮件地址查询自定义头像URL。

    • 如果存在自定义头像,则显示自定义头像;否则,显示Gravatar头像或默认头像。

通过以上代码,用户可以在他们的资料页面输入自定义头像URL,并且该头像将显示在网站的各个位置,而无需使用Gravatar。


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至123@#-@12-3.com举报,一经查实,本站将立刻删除。

共有 30 条评论