要在WordPress中添加本地头像功能以替代Gravatar头像,您可以按照以下步骤操作:
add_action
函数将以下代码添加到主题的functions.php
文件中:function custom_user_profile_fields($user) {
?>
<h3><?php _e('Local Avatar', 'yourtextdomain'); ?></h3>
<table class="formtable">
<tr>
<th>
<label for="local_avatar"><?php _e('Upload Avatar', 'yourtextdomain'); ?></label>
</th>
<td>
<input type="file" name="local_avatar" id="local_avatar" accept="image/" />
<br />
<span class="description"><?php _e('Upload a custom avatar image.', 'yourtextdomain'); ?></span>
</td>
</tr>
</table>
<?php
}
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');
functions.php
文件:function save_custom_user_profile_fields($user_id) {
if (current_user_can('edit_user', $user_id)) {
if (isset($_FILES['local_avatar']['name']) && $_FILES['local_avatar']['name']) {
$upload_dir = wp_upload_dir();
$avatar_file = $_FILES['local_avatar']['tmp_name'];
$avatar_name = sanitize_file_name($_FILES['local_avatar']['name']);
$avatar_path = $upload_dir['path'] . '/' . $avatar_name;
move_uploaded_file($avatar_file, $avatar_path);
update_user_meta($user_id, 'local_avatar', $avatar_path);
}
}
}
add_action('personal_options_update', 'save_custom_user_profile_fields');
add_action('edit_user_profile_update', 'save_custom_user_profile_fields');
function display_local_avatar($avatar, $id_or_email, $size) {
if (is_numeric($id_or_email)) {
$user_id = $id_or_email;
} elseif (is_object($id_or_email)) {
if (!empty($id_or_email>user_id)) {
$user_id = $id_or_email>user_id;
}
} else {
$user = get_user_by('email', $id_or_email);
if ($user) {
$user_id = $user>ID;
}
}
if (isset($user_id)) {
$local_avatar = get_user_meta($user_id, 'local_avatar', true);
if ($local_avatar) {
$avatar = '<img alt="" src="' . esc_url($local_avatar) . '" class="avatar avatar' . $size . '" height="' . $size . '" width="' . $size . '" />';
}
}
return $avatar;
}
add_filter('get_avatar', 'display_local_avatar', 10, 3);
这些代码会创建一个名为"Local Avatar"的自定义字段,允许用户上传本地头像。上传的头像将保存在WordPress的媒体库中。然后,使用get_avatar
过滤器来显示本地头像。
确保替换代码中的'yourtextdomain'以匹配您的主题或插件的文本域。还要确保您的主题支持上传图像,并且具有合适的CSS样式以呈现头像。