Introduction
In WordPress, user avatars are typically managed through the Gravatar service. However, there are scenarios where you might want to allow users to upload and select their own custom avatars directly from the media library. In this tutorial, we'll walk through implementing a custom avatar system with a fallback to Gravatar for users who prefer or only want the default option.
What is the "Custom Avatar from Media Library" Plugin?
The "Custom Avatar from Media Library" plugin allows WordPress users to select a custom avatar from the Media Library instead of relying solely on Gravatar. This provides greater flexibility and control over user profiles, especially for those who prefer not to use external services for their avatars.
Adding the Avatar Selection Field to User Profiles
The plugin adds a new field in the user profile page where users can select a custom avatar from the media library. This is handled by the custom_avatar_media_library_field
function, which renders the selection interface and includes JavaScript to handle media uploads and removal.
Code Example:
1function custom_avatar_media_library_field($user)2{3 // Function content4}5add_action('personal_options', 'custom_avatar_media_library_field');
Saving the Custom Avatar
When a user selects or removes a custom avatar, the plugin saves this preference using user meta. The save_custom_avatar_from_media_library
function handles the saving process when user profile updates occur.
Code Example:
1function save_custom_avatar_from_media_library($user_id)2{3 if (isset($_POST['custom_avatar'])) {4 update_user_meta($user_id, 'custom_avatar', esc_url_raw($_POST['custom_avatar']));5 }6}7add_action('personal_options_update', 'save_custom_avatar_from_media_library');8add_action('edit_user_profile_update', 'save_custom_avatar_from_media_library');
Displaying the Custom Avatar with Gravatar Fallback
To display the custom avatar on the front end, the plugin hooks into the get_avatar
filter. If a user has set a custom avatar, it displays the image; otherwise, it falls back to the default Gravatar.
Code Example:
1function custom_avatar($avatar, $id_or_email, $size)2{3 // Function content4}5add_filter('get_avatar', 'custom_avatar', 10, 3);
Installation and Activation
- Download the Plugin:
- Download the
custom-avatars.php
file and place it in thewp-content/plugins/
directory of your WordPress installation.
- Download the
- Activate the Plugin:
- Navigate to the WordPress admin dashboard.
- Go to Plugins > Installed Plugins.
- Locate "Custom Avatar from Media Library" and click Activate.
Using the Custom Avatar Feature
After activating the plugin, users can set their custom avatar by following these steps:
- Navigate to Profile:
- Click on Users > Your Profile in the WordPress admin dashboard.
- Select an Avatar:
- In the Custom Avatar section, click the Choose Avatar button to open the media library.
- Select an image from the media library or upload a new one.
- Remove Avatar:
- If a custom avatar is set, a Remove Avatar button will appear to allow users to revert to the default Gravatar.
Conclusion
Implementing custom avatars enhances user profiles by giving individuals the freedom to choose their own images without relying solely on Gravatar. This approach promotes a more personalized and engaging user experience. Further enhancements could include allowing users to crop or edit their avatars directly within the profile page.
Full Plugin Code:
1<?php2/*3Plugin Name: Custom Avatar from Media Library4Plugin URI: https://extraparse.com5Description: Allows users to select a custom avatar from the WordPress media library.6Version: 1.07Author: George8Author URI: https://extraparse.com9License: GPL210*/11
12function custom_avatar_media_library_field($user)13{14 $avatar_url = get_user_meta($user->ID, 'custom_avatar', true);15 ?>16 <table class="form-table">17 <tr>18 <th><label for="custom_avatar">Wybierz Avatar</label></th>19 <td>20 <img id="custom_avatar_preview" src="<?php echo esc_url($avatar_url ? $avatar_url : ''); ?>"21 style="width: 100px; height: 100px; <?php echo !$avatar_url ? 'display:none;' : ''; ?>" />22 <br>23 <input type="hidden" name="custom_avatar" id="custom_avatar" value="<?php echo esc_url($avatar_url); ?>" />24 <button type="button" class="button" id="custom_avatar_button">Wybierz Avatar</button>25 <button type="button" class="button" id="remove_custom_avatar"26 style="<?php echo !$avatar_url ? 'display:none;' : ''; ?>">Usuń Avatar</button>27 </td>28 </tr>29 </table>30 <script>31 jQuery(document).ready(function ($) {32 var mediaUploader;33
34 $('#custom_avatar_button').click(function (e) {35 e.preventDefault();36 if (mediaUploader) {37 mediaUploader.open();38 return;39 }40 mediaUploader = wp.media.frames.file_frame = wp.media({41 title: 'Choose Avatar',42 button: { text: 'Choose Avatar' },43 multiple: false44 });45 mediaUploader.on('select', function () {46 var attachment = mediaUploader.state().get('selection').first().toJSON();47 $('#custom_avatar').val(attachment.url);48 $('#custom_avatar_preview').attr('src', attachment.url).show();49 $('#remove_custom_avatar').show();50 });51 mediaUploader.open();52 });53
54 $('#remove_custom_avatar').click(function (e) {55 e.preventDefault();56 $('#custom_avatar').val('');57 $('#custom_avatar_preview').hide();58 $(this).hide();59 });60 });61 </script>62 <?php63}64add_action('personal_options', 'custom_avatar_media_library_field');65
66
67
68
69// Zapisanie własnego Avatara70
71function save_custom_avatar_from_media_library($user_id)72{73 if (isset($_POST['custom_avatar'])) {74 update_user_meta($user_id, 'custom_avatar', esc_url_raw($_POST['custom_avatar']));75 }76}77add_action('personal_options_update', 'save_custom_avatar_from_media_library');78add_action('edit_user_profile_update', 'save_custom_avatar_from_media_library');79
80
81
82
83// Display the custom avatar84function custom_avatar($avatar, $id_or_email, $size)85{86 $user_id = null;87
88 if (is_numeric($id_or_email)) {89 $user_id = $id_or_email;90 } elseif (is_object($id_or_email) && isset($id_or_email->user_id)) {91 $user_id = $id_or_email->user_id;92 } elseif (is_string($id_or_email) && filter_var($id_or_email, FILTER_VALIDATE_EMAIL)) {93 $user = get_user_by('email', $id_or_email);94 if ($user) {95 $user_id = $user->ID;96 }97 }98
99 if ($user_id) {100 $custom_avatar = get_user_meta($user_id, 'custom_avatar', true);101 if ($custom_avatar) {102 return sprintf(103 '<img src="%s" class="avatar avatar-%s photo" width="%s" height="%s" alt="User Avatar" />',104 esc_url($custom_avatar),105 esc_attr($size),106 esc_attr($size),107 esc_attr($size)108 );109 }110 }111
112 return $avatar;113}114add_filter('get_avatar', 'custom_avatar', 10, 3);115
116?>
Comments
You must be logged in to comment.
Loading comments...