Hi @michalrama,
You can use below code to add/change user’s avatar icons.
Instruction:
- Copy code and paste in your active theme’s functions.php file or create plugin
- Go to user profile
- Scroll down to end of the page
- Upload user’s avatar
- Click on Update Profile button.
<?php
// Add custom avatar field to user profile
add_action('show_user_profile', 'custom_avatar_field');
add_action('edit_user_profile', 'custom_avatar_field');
function custom_avatar_field($user) {
$avatar = get_user_meta($user->ID, 'custom_avatar', true);
?>
<h3>Custom Avatar</h3>
<table class="form-table">
<tr>
<th><label for="custom_avatar">Upload Avatar</label></th>
<td>
<input type="file" name="custom_avatar" id="custom_avatar" /><br />
<?php if ($avatar) { ?>
<img src="<?php echo esc_url($avatar); ?>" width="96" style="border-radius: 50%;" /><br />
<input type="checkbox" name="remove_avatar" value="1" /> Remove Avatar
<?php } ?>
</td>
</tr>
</table>
<?php
}
// Save custom avatar using profile update hooks
add_action('personal_options_update', 'save_custom_avatar');
add_action('edit_user_profile_update', 'save_custom_avatar');
function save_custom_avatar($user_id) {
if (!empty($_FILES['custom_avatar']['name'])) {
$upload = wp_upload_bits($_FILES['custom_avatar']['name'], null, file_get_contents($_FILES['custom_avatar']['tmp_name']));
if (!$upload['error']) {
update_user_meta($user_id, 'custom_avatar', $upload['url']);
}
}
if (isset($_POST['remove_avatar'])) {
delete_user_meta($user_id, 'custom_avatar');
}
}
// Display custom avatar
add_filter('get_avatar', 'custom_avatar', 10, 5);
function custom_avatar($avatar, $id_or_email, $size, $default, $alt) {
$user = is_numeric($id_or_email) ? get_user_by('id', (int)$id_or_email) : get_user_by('email', $id_or_email);
$custom_avatar = $user ? get_user_meta($user->ID, 'custom_avatar', true) : false;
if ($custom_avatar) {
$avatar = '<img src="' . esc_url($custom_avatar) . '" alt="' . esc_attr($alt) . '" width="' . (int)$size . '" style="border-radius: 50%;" />';
}
return $avatar;
}
function custom_avatar_enqueue_script() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#your-profile').attr('enctype', 'multipart/form-data');
});
</script>
<?php
}
add_action('admin_footer', 'custom_avatar_enqueue_script');