How to Change the Default Gravatar Using Custom User Profile Field on WordPress

How-to-Change-the-Default-Gravatar-Using-Custom-User-Profile-Field-on-WordPress
448 Views

If you’re using WordPress to power your website, you may have noticed that the default gravatar image used for users who don’t have a custom avatar can be a bit bland.

Fortunately, WordPress makes it easy to change the default gravatar using a custom user profile field. In this article, we’ll walk you through the steps you need to follow to change the default gravatar using a custom user profile field.

Step1: Enqueueing Basics With admin_enqueue_scripts

<?php
add_action( 'admin_enqueue_scripts', 'cxc_gravatar_media_files_call_back' );
function cxc_gravatar_media_files_call_back() {
	if ( ! did_action( 'wp_enqueue_media' ) ) {
		wp_enqueue_media();
	}
}
?>

Step 2: Media Upload Functions

<?php
function multi_media_uploader_field( $name, $value = '' ) {
	$image = '">Add Media';
	$image_str = '';
	$image_size = 'full';
	$display = 'none';
	$value = explode(',', $value);

	if (!empty($value)) {
		foreach ($value as $values) {
			if ($image_attributes = wp_get_attachment_image_src($values, $image_size)) {
				$image_str .= '<li data-attechment-id=' . $values . '><a href="' . $image_attributes[0] . '" target="_blank"><img src="' . $image_attributes[0] . '" width="50" /></a><i class="dashicons dashicons-no delete-img"></i></li>';
			}
		}
	}

	if( $image_str ) {
		$display = 'inline-block';
	}

	return '<div class="cxc-multi-upload-medias"><ul>' . $image_str . '</ul><a href="#" class="cxc_multi_upload_image_button button' . $image . '</a><input type="hidden" class="attechments-ids ' . $name . '" name="' . $name . '"  value="' . esc_attr(implode(',', $value)) . '" /><a href="javascript:;" class="cxc_multi_remove_image_button button" style="display:inline-block;display:' . $display . '">Remove media</a></div>';
}
?>

This code defines a PHP function called multi_media_uploader_field. The purpose of this function is to create a field that allows users to upload multiple media files, such as images or videos, and store their IDs as a comma-separated string in a hidden input field.

Also read: How to change title and sub-title related products in WooCommerce

Step 3: function for adding extra fields in Edit User Section

<?php
add_action( 'show_user_profile', 'cxc_set_gravatar_custom_user_profile_fields' );
add_action( 'edit_user_profile', 'cxc_set_gravatar_custom_user_profile_fields' );
function cxc_set_gravatar_custom_user_profile_fields( $user ) {
	?>	

	<style type="text/css">
		.cxc-multi-upload-medias ul li .delete-img { position: absolute; right: 3px; top: 2px; background: aliceblue; border-radius: 50%; cursor: pointer; font-size: 14px; line-height: 20px; color: red; }
		.cxc-multi-upload-medias ul li { width: 120px; display: inline-block; vertical-align: middle; margin: 5px; position: relative; }
		.cxc-multi-upload-medias ul li img { width: 100%; }
	</style>

	<script type="text/javascript">
		jQuery(function ($) {
      	/*
       	 * Select/Upload image(s) event
       	 */
			$('body').on('click', '.cxc_multi_upload_image_button', function (e) {
				e.preventDefault();

				var button = $(this),
				custom_uploader = wp.media({
					title: 'Insert image',        
					button: {
						text: 'Use this image' 
					},
					multiple: false 
				});

				custom_uploader.on('select', function () { 
					var attech_ids = '';
					attachments
					var attachments = custom_uploader.state().get('selection'),
					attachment_ids = new Array(),
					i = 0;
					$(button).siblings('ul').empty();
					attachments.each(function (attachment) {
						attachment_ids[i] = attachment['id'];
						attech_ids += ',' + attachment['id'];
						if (attachment.attributes.type == 'image') {
							$(button).siblings('ul').append('<li data-attechment-id="' + attachment['id'] + '"><a href="' + attachment.attributes.url + '" target="_blank"><img class="true_pre_image" src="' + attachment.attributes.url + '" /></a><i class=" dashicons  dashicons-no delete-img"></i></li>');
						} else {
							$(button).siblings('ul').append('<li data-attechment-id="' + attachment['id'] + '"><a href="' + attachment.attributes.url + '" target="_blank"><img class="true_pre_image" src="' + attachment.attributes.icon + '" /></a><i class=" dashicons  dashicons-no delete-img"></i></li>');
						}

						i++;
					});

					$(button).siblings('.attechments-ids').attr('value', attachment_ids);
					$(button).siblings('.cxc_multi_remove_image_button').show();

				});
				custom_uploader.on('open',function() {
					var selection = custom_uploader.state().get('selection');
					var ids_value = $(button).siblings('.attechments-ids').val();

					if(ids_value.length > 0) {
						var ids = ids_value.split(',');

						ids.forEach(function(id) {
							attachment = wp.media.attachment(id);
							attachment.fetch();
							selection.add(attachment ? [attachment] : []);
						});
					}
				});
				custom_uploader.open();
			});

      		/*
       		* Remove image event
       		*/
			$('body').on('click', '.cxc_multi_remove_image_button', function (e) {
				e.preventDefault();
				$(this).hide().prev().val('').prev().addClass('button').html('Add  Media');
				$(this).parent().find('ul').empty();
				return false;
			});

			jQuery(document).on('click', '.cxc-multi-upload-medias ul li i.delete-img', function () {
				var ids = [];
				var attach_id =  jQuery(this).parents('li').attr('data-attechment-id');
				jQuery('.cxc-multi-upload-medias ul li').each(function () {
					if( attach_id != jQuery(this).attr('data-attechment-id') ){
						ids.push(jQuery(this).attr('data-attechment-id'));  
					}
				});

				jQuery(this).parents('.cxc-multi-upload-medias').find('input[type="hidden"]').val(ids);
				jQuery(this).parent().remove();               
			});

		});
	</script>

	<?php $cxc_gravatar_image = get_user_meta( $user->ID, 'cxc_gravatar_image', true ); ?>

	<table class="form-table">
		<tr>
			<th>
				<label for="cxc_gravatar_image"><?php esc_html_e( 'Gravatar Image' ); ?></label>
			</th>
			<td>
				<?php echo multi_media_uploader_field( 'cxc_gravatar_image', $cxc_gravatar_image ); ?>
			</td>
		</tr>
	</table>

	<?php

}
?>

This code is used to add a custom user profile field to WordPress. Specifically, it adds a “Gravatar Image” field to the user profile page, allowing users to upload and select an image to use as their Gravatar.

Also read: How to restrict dashboard access to Admins only in WordPress

Step 4: function for saving extra fields in Edit User Section

<?php
add_action( 'personal_options_update', 'cxc_save_gravatar_user_profile_fields' );
add_action( 'edit_user_profile_update', 'cxc_save_gravatar_user_profile_fields' );

function cxc_save_gravatar_user_profile_fields( $user_id ) {

	if( ! isset( $_POST[ '_wpnonce' ] ) || ! wp_verify_nonce( $_POST[ '_wpnonce' ], 'update-user_' . $user_id ) ) {
		return;
	}
	
	if( ! current_user_can( 'edit_user', $user_id ) ) {
		return;
	}

	update_user_meta( $user_id, 'cxc_gravatar_image', sanitize_text_field( $_POST[ 'cxc_gravatar_image' ] ) );

}
?>

This code is a PHP function that is designed to save user profile data to the WordPress database when the user profile is updated. Specifically, it saves data related to a user’s Gravatar image.

Also read: How to Get Category ID by Category Name in WordPress

Step 5: Function for showing custom gravatar image

<?php
add_filter( 'get_avatar_url', 'cxc_get_gravatar_image_url_call_back', 10, 3 );
function cxc_get_gravatar_image_url_call_back( $url, $id_or_email, $args ) {

	$id = '';
	$user_id = isset( $id_or_email->user_id ) ? $id_or_email->user_id : '';

	if ( is_numeric( $id_or_email ) ) {
		$id = (int) $id_or_email;
	} elseif ( is_object( $id_or_email ) ) {
		if ( ! empty( $id_or_email->user_id ) ) {
			$id = (int) $id_or_email->user_id;
		}
	} else {
		$user = get_user_by( 'email', $id_or_email );
		$id = !empty( $user ) ?  $user->data->ID : '';
	}

	$img_path = get_user_meta( $id, 'cxc_gravatar_image', true );
	if( $img_path ){
		$user_image = wp_get_attachment_image_src( $img_path, 'full' );

		if( $user_image ){
			$custom_url = $user_image[0];	
		}

		return esc_url_raw( $custom_url );

	}

	return esc_url_raw( $url ); 

}
?>

This code is used to customize the default avatar image that appears on WordPress websites. The function cxc_get_gravatar_image_url_call_back is a filter that modifies the URL of the avatar image.

The function first checks if the user ID or email is provided, and then gets the path to the custom avatar image using the get_user_meta function. If the custom image exists, the function uses wp_get_attachment_image_src to get the URL of the custom image and returns it.

FAQs

How can I update my WordPress personal image without using Gravatar?

Simply navigate to the Users > Profile tab. You can add a picture from your computer or use one from the media collection from this page. Don’t neglect to save your adjustments by clicking the Update Profile option.

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published. Required fields are marked *