Advertisement
  1. Code
  2. Plugins

How to Create a WordPress Avatar Management Plugin: Finishing Touches

Scroll to top
Read Time: 29 min
This post is part of a series called How to Create a WordPress Avatar Management Plugin from Scratch.
How to Create a WordPress Avatar Management Plugin from Scratch: Getting Started

Avatar Manager for WordPress is a sweet and simple plugin for storing avatars locally and more. Easily.

Enhance your WordPress website by letting your users choose between using Gravatar or a self-hosted avatar image right from their profile screen. Improved workflow, on-demand image generation and custom user permissions under a native interface. Say hello to the Avatar Manager plugin.


A Quick Recap

In the first part of our tutorial, we reviewed:

  • what is a WordPress plugin;
  • how to create a basic WordPress plugin, choose an appropriate license and format for the version number;
  • what are action and filter hooks and how to use them to create our plugin;
  • how to add new settings to existing settings screens;
  • how to make a plugin more flexible by using custom options.

Today, we'll take things further and wrap up our plugin: we'll handle avatar uploads and on-demand image generation, internationalize our plugin and much more.


Step 1. Resizing an Avatar Image

Let's start by writing the following function:

1
/**

2
 * Generates a resized copy of the specified avatar image.

3
 *

4
 * @uses wp_upload_dir() For retrieving path information on the currently

5
 * configured uploads directory.

6
 * @uses wp_basename() For i18n friendly version of basename().

7
 * @uses wp_get_image_editor() For retrieving a WP_Image_Editor instance and

8
 * loading a file into it.

9
 * @uses is_wp_error() For checking whether the passed variable is a WordPress

10
 * Error.

11
 * @uses do_action() For calling the functions added to an action hook.

12
 *

13
 * @since Avatar Manager 1.0.0

14
 *

15
 * @param string $url URL of the avatar image to resize.

16
 * @param int $size Size of the new avatar image.

17
 * @return array Array with the URL of the new avatar image.

18
 */
19
function avatar_manager_avatar_resize( $url, $size ) {
20
	// Retrieves path information on the currently configured uploads directory.

21
	$upload_dir = wp_upload_dir();
22
23
	$filename  = str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], $url );
24
	$pathinfo  = pathinfo( $filename );
25
	$dirname   = $pathinfo['dirname'];
26
	$extension = $pathinfo['extension'];
27
28
	// i18n friendly version of basename().

29
	$basename = wp_basename( $filename, '.' . $extension );
30
31
	$suffix    = $size . 'x' . $size;
32
	$dest_path = $dirname . '/' . $basename . '-' . $suffix . '.' . $extension;
33
	$avatar    = array();
34
35
	if ( file_exists( $dest_path ) ) {
36
		$avatar['url']  = str_replace( $upload_dir['basedir'], $upload_dir['baseurl'], $dest_path );
37
		$avatar['skip'] = true;
38
	} else {
39
		// Retrieves a WP_Image_Editor instance and loads a file into it.

40
		$image = wp_get_image_editor( $filename );
41
42
		if ( ! is_wp_error( $image ) ) {
43
			// Resizes current image.

44
			$image->resize( $size, $size, true );
45
46
			// Saves current image to file.

47
			$image->save( $dest_path );
48
49
			$avatar['url']  = str_replace( $upload_dir['basedir'], $upload_dir['baseurl'], $dest_path );
50
			$avatar['skip'] = false;
51
		}
52
	}
53
54
	// Calls the functions added to avatar_manager_avatar_resize action hook.

55
	do_action( 'avatar_manager_avatar_resize', $url, $size );
56
57
	return $avatar;
58
}

Summary

  • The avatar_manager_avatar_resize() function generates a resized copy of the specified avatar image.
  • The wp_upload_dir() call returns an array containing path information on the currently configured uploads directory.
  • The str_replace() function replaces all occurrences of the search string with the replacement string.
  • The pathinfo() function returns information about a file path.
  • The wp_basename() function is the i18n friendly version of basename() which returns the trailing name component of a path.
  • The file_exists() function checks whether a file or directory exists.
  • The skip flag is set to true if the destination image file already exists, else a new image is generated.
  • The wp_get_image_editor() function returns a WP_Image_Editor instance and loads a file into it. With that we can manipulate the image by calling methods on it.
  • The is_wp_error() function checks whether the passed variable is a WordPress error.
  • Then, we resize and save the image by calling the resize() and save() methods of the $image object.
  • The do_action() executes a hook created by add_action(); this allows themes and plugins to hook to the avatar_manager_avatar_resize action which is triggered after resizing an avatar image.

Step 2. Deleting an Avatar Image

Before taking care of profile updates, we need to define one more function:

1
/**

2
 * Deletes an avatar image based on attachment ID.

3
 *

4
 * @uses get_post_meta() For retrieving attachment meta fields.

5
 * @uses wp_upload_dir() For retrieving path information on the currently

6
 * configured uploads directory.

7
 * @uses delete_post_meta() For deleting attachment meta fields.

8
 * @uses get_users() For retrieving an array of users.

9
 * @uses delete_user_meta() For deleting user meta fields.

10
 * @uses do_action() For calling the functions added to an action hook.

11
 *

12
 * @since Avatar Manager 1.0.0

13
 *

14
 * @param int $attachment_id An attachment ID

15
 */
16
function avatar_manager_delete_avatar( $attachment_id ) {
17
	// Retrieves attachment meta field based on attachment ID.

18
	$is_custom_avatar = get_post_meta( $attachment_id, '_avatar_manager_is_custom_avatar', true );
19
20
	if ( ! $is_custom_avatar )
21
		return;
22
23
	// Retrieves path information on the currently configured uploads directory.

24
	$upload_dir = wp_upload_dir();
25
26
	// Retrieves attachment meta field based on attachment ID.

27
	$custom_avatar = get_post_meta( $attachment_id, '_avatar_manager_custom_avatar', true );
28
29
	if ( is_array( $custom_avatar ) ) {
30
		foreach ( $custom_avatar as $file ) {
31
			if ( ! $file['skip'] ) {
32
				$file = str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], $file['url'] );
33
				@unlink( $file );
34
			}
35
		}
36
	}
37
38
	// Deletes attachment meta fields based on attachment ID.

39
	delete_post_meta( $attachment_id, '_avatar_manager_custom_avatar' );
40
	delete_post_meta( $attachment_id, '_avatar_manager_custom_avatar_rating' );
41
	delete_post_meta( $attachment_id, '_avatar_manager_is_custom_avatar' );
42
43
	// An associative array with criteria to match.

44
	$args = array(
45
		'meta_key'   => 'avatar_manager_custom_avatar',
46
		'meta_value' => $attachment_id
47
	);
48
49
	// Retrieves an array of users matching the criteria given in $args.

50
	$users = get_users( $args );
51
52
	foreach ( $users as $user ) {
53
		// Deletes user meta fields based on user ID.

54
		delete_user_meta( $user->ID, 'avatar_manager_avatar_type' );
55
		delete_user_meta( $user->ID, 'avatar_manager_custom_avatar' );
56
	}
57
58
	// Calls the functions added to avatar_manager_delete_avatar action hook.

59
	do_action( 'avatar_manager_delete_avatar', $attachment_id );
60
}
61
62
add_action( 'delete_attachment', 'avatar_manager_delete_avatar' );

Summary

  • The delete_attachment action hook is called when an attachment is deleted by wp_delete_attachment().
  • The get_post_meta() returns the values of the custom fields with the specified key from the specified post. First, we test if the attachment with the specified ID is an avatar image.
  • The is_array() call finds whether a variable is an array.
  • Then, we use the unlink() function to delete the avatar image including its resized copies, but skipping those with the skip flag set to true.
  • The delete_post_meta() function deletes all custom fields with the specified key from the specified post.
  • The get_users() function retrieves an array of users matching the criteria given in $args.
  • The delete_user_meta() function removes metadata matching criteria from a user.
  • Lastly, we execute the avatar_manager_delete_avatar action hook.

Step 3. Updating a User Profile

When updating a user profile, we need not only to save the options changed by the user but to handle avatar uploads and removals too. Let's do it:

1
/**

2
 * Updates user profile based on user ID.

3
 *

4
 * @uses avatar_manager_get_options() For retrieving plugin options.

5
 * @uses sanitize_text_field() For sanitizing a string from user input or from

6
 * the database.

7
 * @uses update_user_meta() For updating user meta fields.

8
 * @uses get_user_meta() For retrieving user meta fields.

9
 * @uses update_post_meta() For updating attachment meta fields.

10
 * @uses wp_handle_upload() For handling PHP uploads in WordPress.

11
 * @uses wp_die() For killing WordPress execution and displaying HTML error

12
 * message.

13
 * @uses __() For retrieving the translated string from the translate().

14
 * @uses avatar_manager_delete_avatar() For deleting an avatar image.

15
 * @uses wp_insert_attachment() For inserting an attachment into the media

16
 * library.

17
 * @uses wp_generate_attachment_metadata() For generating metadata for an

18
 * attachment.

19
 * @uses wp_update_attachment_metadata() For updating metadata for an

20
 * attachment.

21
 * @uses avatar_manager_avatar_resize() For generating a resized copy of the

22
 * specified avatar image.

23
 * @uses avatar_manager_delete_avatar() For deleting an avatar image based on

24
 * attachment ID.

25
 * @uses get_edit_user_link() For getting the link to the users edit profile

26
 * page in the WordPress admin.

27
 * @uses add_query_arg() For retrieving a modified URL (with) query string.

28
 * @uses wp_redirect() For redirecting the user to a specified absolute URI.

29
 *

30
 * @since Avatar Manager 1.0.0

31
 *

32
 * @param int $user_id User to update.

33
 */
34
function avatar_manager_edit_user_profile_update( $user_id ) {
35
	// Retrieves plugin options.

36
	$options = avatar_manager_get_options();
37
38
	// Sanitizes the string from user input.

39
	$avatar_type = isset( $_POST['avatar_manager_avatar_type'] ) ? sanitize_text_field( $_POST['avatar_manager_avatar_type'] ) : 'gravatar';
40
41
	// Updates user meta field based on user ID.

42
	update_user_meta( $user_id, 'avatar_manager_avatar_type', $avatar_type );
43
44
	// Retrieves user meta field based on user ID.

45
	$custom_avatar = get_user_meta( $user_id, 'avatar_manager_custom_avatar', true );
46
47
	if ( ! empty( $custom_avatar ) ) {
48
		// Sanitizes the string from user input.

49
		$custom_avatar_rating = isset( $_POST['avatar_manager_custom_avatar_rating'] ) ? sanitize_text_field( $_POST['avatar_manager_custom_avatar_rating'] ) : 'G';
50
51
		// Updates attachment meta field based on attachment ID.

52
		update_post_meta( $custom_avatar, '_avatar_manager_custom_avatar_rating', $custom_avatar_rating );
53
	}
54
55
	...
56
}
57
58
add_action( 'edit_user_profile_update', 'avatar_manager_edit_user_profile_update' );
59
add_action( 'personal_options_update', 'avatar_manager_edit_user_profile_update' );

Summary

Handling Avatar Uploads

To handle avatar uploads, write the following code:

1
if ( isset( $_POST['avatar-manager-upload-avatar'] ) && $_POST['avatar-manager-upload-avatar'] ) {
2
	if ( ! function_exists( 'wp_handle_upload' ) )
3
		require_once( ABSPATH . 'wp-admin/includes/file.php' );
4
5
	// An associative array with allowed MIME types.

6
	$mimes = array(
7
		'bmp'  => 'image/bmp',
8
		'gif'  => 'image/gif',
9
		'jpe'  => 'image/jpeg',
10
		'jpeg' => 'image/jpeg',
11
		'jpg'  => 'image/jpeg',
12
		'png'  => 'image/png',
13
		'tif'  => 'image/tiff',
14
		'tiff' => 'image/tiff'
15
	);
16
17
	// An associative array to override default variables.

18
	$overrides = array(
19
		'mimes'     => $mimes,
20
		'test_form' => false
21
	);
22
23
	// Handles PHP uploads in WordPress.

24
	$avatar = wp_handle_upload( $_FILES['avatar_manager_import'], $overrides );
25
26
	if ( isset( $avatar['error'] ) )
27
		// Kills WordPress execution and displays HTML error message.

28
		wp_die( $avatar['error'],  __( 'Image Upload Error', 'avatar-manager' ) );
29
30
	if ( ! empty( $custom_avatar ) )
31
		// Deletes users old avatar image.

32
		avatar_manager_delete_avatar( $custom_avatar );
33
34
	// An associative array about the attachment.

35
	$attachment = array(
36
		'guid'           => $avatar['url'],
37
		'post_content'   => $avatar['url'],
38
		'post_mime_type' => $avatar['type'],
39
		'post_title'     => basename( $avatar['file'] )
40
	);
41
42
	// Inserts the attachment into the media library.

43
	$attachment_id = wp_insert_attachment( $attachment, $avatar['file'] );
44
45
	// Generates metadata for the attachment.

46
	$attachment_metadata = wp_generate_attachment_metadata( $attachment_id, $avatar['file'] );
47
48
	// Updates metadata for the attachment.

49
	wp_update_attachment_metadata( $attachment_id, $attachment_metadata );
50
51
	$custom_avatar = array();
52
53
	// Generates a resized copy of the avatar image.

54
	$custom_avatar[ $options['default_size'] ] = avatar_manager_avatar_resize( $avatar['url'], $options['default_size'] );
55
56
	// Updates attachment meta fields based on attachment ID.

57
	update_post_meta( $attachment_id, '_avatar_manager_custom_avatar', $custom_avatar );
58
	update_post_meta( $attachment_id, '_avatar_manager_custom_avatar_rating', 'G' );
59
	update_post_meta( $attachment_id, '_avatar_manager_is_custom_avatar', true );
60
61
	// Updates user meta fields based on user ID.

62
	update_user_meta( $user_id, 'avatar_manager_avatar_type', 'custom' );
63
	update_user_meta( $user_id, 'avatar_manager_custom_avatar', $attachment_id );
64
}

Summary

  • The function_exists() returns true if the given function has been defined, then the require_once() statement checks if the specified file has already been included, and if so, doesn't include it again.
  • The wp_handle_upload() function handles PHP uploads in WordPress, sanitizing file names, checking extensions for mime type, and moving the file to the appropriate directory within the uploads directory.
  • Before adding the new avatar image, we call the avatar_manager_delete_avatar() function to delete the old avatar, if any is set.
  • The wp_insert_attachment() function inserts an attachment into the media library.
  • The wp_generate_attachment_metadata() function generates metadata for an image attachment; it also creates a thumbnail and other intermediate sizes of the image attachment based on the sizes defined on the Settings Media Screen.
  • The wp_update_attachment_metadata() function updates metadata for an attachment.
  • Next, we call the avatar_manager_avatar_resize() function to generate a copy of the avatar image at default size.
  • Lastly, we update the metadata for the attachment and for the user currently being edited.

Removing an Avatar Image

Now, it's time to make the plugin to actually delete an avatar image when requested:

1
if ( isset( $_GET['avatar_manager_action'] ) && $_GET['avatar_manager_action'] ) {
2
	global $wp_http_referer;
3
4
	$action = $_GET['avatar_manager_action'];
5
6
	switch ( $action ) {
7
		case 'remove-avatar':
8
			// Deletes avatar image based on attachment ID.

9
			avatar_manager_delete_avatar( $_GET['avatar_manager_custom_avatar'] );
10
11
			break;
12
	}
13
14
	// Gets the link to the users edit profile page in the WordPress admin.

15
	$edit_user_link = get_edit_user_link( $user_id );
16
17
	// Retrieves a modified URL (with) query string.

18
	$redirect = add_query_arg( 'updated', true, $edit_user_link );
19
20
	if ( $wp_http_referer )
21
		// Retrieves a modified URL (with) query string.

22
		$redirect = add_query_arg( 'wp_http_referer', urlencode( $wp_http_referer ), $redirect );
23
24
	// Redirects the user to a specified absolute URI.

25
	wp_redirect( $redirect );
26
27
	exit;
28
}

Summary

  • If the value of the requested action is remove-avatar we call the avatar_manager_delete_avatar() to delete the specified avatar image.
  • The get_edit_user_link() function gets the link to the users edit profile page in the WordPress admin.
  • The urlencode() function encodes a string to be used in a query part of a URL.
  • At the end of the function, we call the wp_redirect() function to redirect the user back to the updated user profile.
  • The exit call terminates the execution of the script; it's a language construct and it can be called without parentheses if no status is passed.

Step 4. Retrieving a Custom Avatar Image

Next, we're going to write a helper function for retrieving a custom avatar image:

1
/**

2
 * Returns user custom avatar based on user ID.

3
 *

4
 * @uses get_option() For getting values for a named option.

5
 * @uses avatar_manager_get_options() For retrieving plugin options.

6
 * @uses get_userdata() For retrieving user data by user ID.

7
 * @uses is_ssl() For checking if SSL is being used.

8
 * @uses add_query_arg() For retrieving a modified URL (with) query string.

9
 * @uses esc_attr() For escaping HTML attributes.

10
 * @uses get_user_meta() For retrieving user meta fields.

11
 * @uses get_post_meta() For retrieving attachment meta fields.

12
 * @uses wp_get_attachment_image_src() For retrieving an array with the image

13
 * attributes "url", "width" and "height", of an image attachment file.

14
 * @uses avatar_manager_avatar_resize() For generating a resized copy of the

15
 * specified avatar image.

16
 * @uses update_post_meta() For updating attachment meta fields.

17
 * @uses apply_filters() For calling the functions added to a filter hook.

18
 *

19
 * @since Avatar Manager 1.0.0

20
 *

21
 * @param int $user_id User to update.

22
 * @param int $size Size of the avatar image

23
 * @param string $default URL to a default image to use if no avatar is

24
 * available.

25
 * @param string $alt Alternative text to use in image tag. Defaults to blank.

26
 * @return string <img> tag for the user's avatar.

27
 */
28
function avatar_manager_get_custom_avatar( $user_id, $size = '', $default = '', $alt = false ) {
29
	// Returns if showing avatars is not enabled.

30
	if ( ! get_option( 'show_avatars' ) )
31
		return false;
32
33
	// Retrieves plugin options.

34
	$options = avatar_manager_get_options();
35
36
	if ( empty( $size ) || ! is_numeric( $size ) ) {
37
		$size = $options['avatar-manager-default-size'];
38
	} else {
39
		$size = absint( $size );
40
41
		if ( $size < 1 )
42
			$size = 1;
43
		elseif ( $size > 512 )
44
			$size = 512;
45
	}
46
47
	// Retrieves user data by user ID.

48
	$user = get_userdata( $user_id );
49
50
	// Returns if no user data was retrieved.

51
	if ( empty( $user ) )
52
		return false;
53
54
	$email = $user->user_email;
55
56
	if ( empty( $default ) ) {
57
		// Retrieves values for the named option.

58
		$avatar_default = get_option( 'avatar_default' );
59
60
		if ( empty( $avatar_default ) )
61
			$default = 'mystery';
62
		else
63
			$default = $avatar_default;
64
	}
65
66
	$email_hash = md5( strtolower( trim( $email ) ) );
67
68
	if ( is_ssl() )
69
		$host = 'https://secure.gravatar.com';
70
	else
71
		$host = sprintf( 'http://%d.gravatar.com', ( hexdec( $email_hash[0] ) % 2 ) );
72
73
	if ( $default == 'mystery' )
74
		$default = $host . '/avatar/ad516503a11cd5ca435acc9bb6523536?s=' . $size;
75
	elseif ( $default == 'gravatar_default' )
76
		$default = '';
77
	elseif ( strpos( $default, 'http://' ) === 0 )
78
		// Retrieves a modified URL (with) query string.

79
		$default = add_query_arg( 's', $size, $default );
80
81
	if ( $alt === false )
82
		$alt = '';
83
	else
84
		// Escapes HTML attributes.

85
		$alt = esc_attr( $alt );
86
87
	// Retrieves values for the named option.

88
	$avatar_rating = get_option( 'avatar_rating' );
89
90
	// Retrieves user meta field based on user ID.

91
	$custom_avatar = get_user_meta( $user_id, 'avatar_manager_custom_avatar', true );
92
93
	// Returns if no attachment ID was retrieved.

94
	if ( empty( $custom_avatar ) )
95
		return false;
96
97
	// Retrieves attachment meta field based on attachment ID.

98
	$custom_avatar_rating = get_post_meta( $custom_avatar, '_avatar_manager_custom_avatar_rating', true );
99
100
	$ratings['G']  = 1;
101
	$ratings['PG'] = 2;
102
	$ratings['R']  = 3;
103
	$ratings['X']  = 4;
104
105
	if ( $ratings[ $custom_avatar_rating ] <= $ratings[ $avatar_rating ] ) {
106
		// Retrieves attachment meta field based on attachment ID.

107
		$avatar = get_post_meta( $custom_avatar, '_avatar_manager_custom_avatar', true );
108
109
		if ( empty( $avatar[ $size ] ) ) {
110
			// Retrieves an array with the image attributes "url", "width"

111
			// and "height", of the image attachment file.

112
			$url = wp_get_attachment_image_src( $custom_avatar, 'full' );
113
114
			// Generates a resized copy of the avatar image.

115
			$avatar[ $size ] = avatar_manager_avatar_resize( $url[0], $size );
116
117
			// Updates attachment meta field based on attachment ID.

118
			update_post_meta( $custom_avatar, '_avatar_manager_custom_avatar', $avatar );
119
		}
120
121
		$src    = $avatar[ $size ]['url'];
122
		$avatar = '<img alt="' . $alt . '" class="avatar avatar-' . $size . ' photo avatar-default" height="' . $size . '" src="' . $src . '" width="' . $size . '">';
123
	} else {
124
		$src  = $host . '/avatar/';
125
		$src .= $email_hash;
126
		$src .= '?s=' . $size;
127
		$src .= '&d=' . urlencode( $default );
128
		$src .= '&forcedefault=1';
129
130
		$avatar = '<img alt="' . $alt . '" class="avatar avatar-' . $size . ' photo avatar-default" height="' . $size . '" src="' . $src . '" width="' . $size . '">';
131
	}
132
133
	// Calls the functions added to avatar_manager_get_custom_avatar

134
	// filter hook.

135
	return apply_filters( 'avatar_manager_get_custom_avatar', $avatar, $user_id, $size, $default, $alt );
136
}

Summary

  • The avatar_manager_get_custom_avatar function returns a custom avatar image based on user ID or false if showing avatars is not enabled. The function retrieves plugin options, sanitizes the $size parameter and escapes HTML attributes from $alt variable.
  • Then, it retrieves a default image to use instead of the avatar image if the avatar rating doesn't match. A resized copy of the avatar image is generated on-demand if the requested size doesn't match an existing image file.
  • The get_userdata() function returns a WP_User object with the information pertaining to the user whose ID is passed to it.
  • The md5() function returns the MD5 hash for the provided string.
  • The strtolower() function returns the provided string but with all alphabetic characters converted to lowercase.
  • The is_ssl() call checks if SSL is being used.
  • The sprintf() function returns a formatted string.
  • The hexdec() function returns the decimal equivalent of the specified hexadecimal number.
  • The call strpos() finds the numeric position of the first occurrence of needle in the haystack string.
  • The wp_get_attachment_image_src() function returns an array with the image attributes url, width and height, of an image attachment file.
  • Lastly, we use the apply_filters() function to call the functions added to the avatar_manager_get_custom_avatar filter hook.

Step 5. Retrieving an Avatar Image

Basically, the next function is the main function of our plugin:

1
/**

2
 * Returns the avatar for a user who provided a user ID or email address.

3
 *

4
 * @uses get_option() For getting values for a named option.

5
 * @uses avatar_manager_get_options() For retrieving plugin options.

6
 * @uses get_userdata() For retrieving user data by user ID.

7
 * @uses avatar_manager_get_custom_avatar() For retrieving user custom avatar

8
 * based on user ID.

9
 * @uses apply_filters() For calling the functions added to a filter hook.

10
 *

11
 * @since Avatar Manager 1.0.0

12
 *

13
 * @param int|string|object $id_or_email A user ID, email address, or comment

14
 * object.

15
 * @param int $size Size of the avatar image

16
 * @param string $default URL to a default image to use if no avatar is

17
 * available.

18
 * @param string $alt Alternative text to use in image tag. Defaults to blank.

19
 * @return string <img> tag for the user's avatar.

20
 */
21
function avatar_manager_get_avatar( $avatar = '', $id_or_email, $size = '', $default = '', $alt = false ) {
22
	// Returns if showing avatars is not enabled.

23
	if ( ! get_option( 'show_avatars' ) )
24
		return false;
25
26
	// Retrieves plugin options.

27
	$options = avatar_manager_get_options();
28
29
	if ( empty( $size ) || ! is_numeric( $size ) ) {
30
		$size = $options['avatar-manager-default-size'];
31
	} else {
32
		$size = absint( $size );
33
34
		if ( $size < 1 )
35
			$size = 1;
36
		elseif ( $size > 512 )
37
			$size = 512;
38
	}
39
40
	$email = '';
41
42
	if ( is_numeric( $id_or_email ) ) {
43
		$id = (int) $id_or_email;
44
45
		// Retrieves user data by user ID.

46
		$user = get_userdata( $id );
47
48
		if ( $user )
49
			$email = $user->user_email;
50
	} elseif ( is_object( $id_or_email ) ) {
51
		if ( ! empty( $id_or_email->user_id ) ) {
52
			$id = (int) $id_or_email->user_id;
53
54
			// Retrieves user data by user ID.

55
			$user = get_userdata( $id );
56
57
			if ( $user )
58
				$email = $user->user_email;
59
		} elseif ( ! empty( $id_or_email->comment_author_email ) ) {
60
			$email = $id_or_email->comment_author_email;
61
		}
62
	} else {
63
		$email = $id_or_email;
64
65
		if ( $id = email_exists( $email ) )
66
			// Retrieves user data by user ID.

67
			$user = get_userdata( $id );
68
	}
69
70
	if ( isset( $user ) )
71
		$avatar_type = $user->avatar_manager_avatar_type;
72
	else
73
		return $avatar;
74
75
	if ( $avatar_type == 'custom' )
76
		// Retrieves user custom avatar based on user ID.

77
		$avatar = avatar_manager_get_custom_avatar( $user->ID, $size, $default, $alt );
78
79
	// Calls the functions added to avatar_manager_get_avatar filter hook.

80
	return apply_filters( 'avatar_manager_get_avatar', $avatar, $id_or_email, $size, $default, $alt );
81
}
82
83
add_filter( 'get_avatar', 'avatar_manager_get_avatar', 10, 5 );

Summary

  • The avatar_manager_get_avatar() function returns the avatar for a user who provided a user ID or email address, or false if showing avatars is not enabled.
  • We use the get_avatar filter to change the output of the get_avatar() function. Our function retrieves plugin options, sanitizes the $size parameter and finds the ID of the specified user.
  • Then, it returns the result of the avatar_manager_get_custom_avatar() function call, or the unmodified output of the get_avatar() if the user doesn't use a custom avatar.
  • The is_object() call finds whether a variable is an object.
  • The email_exists() function checks whether or not a given email address has already been registered to a username, and returns that users ID, or false if none exists.

To test the result, go to the Users -> Your Profile Screen.

The Avatar Manager plugin options under the User Your Profile ScreenThe Avatar Manager plugin options under the User Your Profile ScreenThe Avatar Manager plugin options under the User Your Profile Screen
The Avatar Manager plugin options under the User Your Profile Screen

Browse for an image an upload it. Now, you should be able to choose between using Gravatar or the custom avatar image you just uploaded.


Step 6. Removing Unnecessary Filter Hooks

If you go to the Settings Discussion Screen you'll notice that the avatars from the Default Avatar setting are replaced with your custom avatar. To fix this issue, we'll restore the default avatars by removing our custom function when it isn't needed with the help of the avatar_defaults filter hook. To do so, add the following code:

1
/**

2
 * Prevents custom avatars from being applied to the Default Avatar setting.

3
 *

4
 * @uses remove_filter() For removing a function attached to a specified action

5
 * hook.

6
 *

7
 * @since Avatar Manager 1.0.0

8
 *

9
 * @param array $avatar_defaults An associative array with default avatars.

10
 * @return array An associative array with default avatars.

11
 */
12
function avatar_manager_avatar_defaults( $avatar_defaults ) {
13
	// Removes the avatar_manager_get_avatar function attached to get_avatar

14
	// action hook.

15
	remove_filter( 'get_avatar', 'avatar_manager_get_avatar' );
16
17
	return $avatar_defaults;
18
}
19
20
add_filter( 'avatar_defaults', 'avatar_manager_avatar_defaults', 10, 1 );

To prevent custom avatars from being applied to the Default Avatar setting, we call the remove_filter() function. It removes a function attached to a specified filter hook. This method can be used to remove default functions attached to a specific filter hook and possibly replace them with a substitute.


Step 7. Displaying Custom Media States

The Media Library Screen allows you to edit, view, and delete images, video, recordings, and files previously uploaded to your blog. To identify an attachment being used as an avatar image, we're going to display a custom media state for it:

1
/**

2
 * Displays media states for avatar images.

3
 *

4
 * @uses get_post_meta() For retrieving attachment meta fields.

5
 * @uses __() For retrieving the translated string from the translate().

6
 * @uses apply_filters() For calling the functions added to a filter hook.

7
 *

8
 * @since Avatar Manager 1.0.0

9
 *

10
 * @param array $media_states An associative array with media states.

11
 * @return array An associative array with media states.

12
 */
13
function avatar_manager_display_media_states( $media_states ) {
14
	global $post;
15
16
	// Retrieves attachment meta field based on attachment ID.

17
	$meta_avatar = get_post_meta( $post->ID, '_avatar_manager_is_custom_avatar', true );
18
19
	if ( ! empty( $meta_avatar ) )
20
		$media_states[] = __( 'Avatar Image', 'avatar-manager' );
21
22
	// Calls the functions added to avatar_manager_display_media_states filter

23
	// hook.

24
	return apply_filters( 'avatar_manager_display_media_states', $media_states );
25
}
26
27
add_filter( 'display_media_states', 'avatar_manager_display_media_states', 10, 1 );

The display_media_states filter is used to display custom media states for attachmets that have been added to the Media Library. We use the $post global variable to grab the ID of the current attachment. If the _avatar_manager_is_custom_avatar custom field isn't empty, the attachment is an avatar image so we add a custom media state for it.

If you don't have any custom avatar image set up, upload one and go to the Media Library Screen.

The Avatar Manager plugin media states under the Media Library ScreenThe Avatar Manager plugin media states under the Media Library ScreenThe Avatar Manager plugin media states under the Media Library Screen
The Avatar Manager plugin media states under the Media Library Screen

Notice that each attachment being used as a custom avatar image does have the Avatar Image string appended next to its filename.


Step 8. Adding the Uninstaller

In order to handle the uninstall process, a plugin should create a file named uninstall.php in the base plugin directory rather than using register_uninstall_hook(). This file will be called, if it exists, during the uninstall process bypassing the uninstall hook. To do so, open avatar-manager/uninstall.php and add the following code:

1
<?php
2
/**

3
 * @package Avatar_Manager

4
 * @subpackage Uninstaller

5
 */
6
7
// Exits if uninstall is not called from WordPress.

8
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) )
9
	exit;
10
11
if ( ! function_exists( 'avatar_manager_delete_avatar' ) )
12
	include_once( 'avatar-manager.php' );
13
14
// Deletes plugin options.

15
delete_option( 'avatar_manager' );
16
17
// An associative array with criteria to match.

18
$args = array(
19
	'meta_key' => 'avatar_manager_custom_avatar'
20
);
21
22
// Retrieves an array of users matching the criteria given in $args.

23
$users = get_users( $args );
24
25
foreach ( $users as $user ) {
26
	// Deletes avatar image based on attachment ID.

27
	avatar_manager_delete_avatar( $user->avatar_manager_custom_avatar );
28
}
29
?>

When using uninstall.php the plugin should always check for the WP_UNINSTALL_PLUGIN constant, before executing. The WP_UNINSTALL_PLUGIN constant is defined by WordPress at runtime during a plugin uninstall and it will not be present if uninstall.php is requested directly. The defined() checks whether a given named constant exists. The include_once statement includes and evaluates the specified file during the execution of the script; if the code from a file has already been included, it will not be included again. The delete_option() function removes a named option from the options database table.


Step 9. Internationalizing and Translating the Plugin

Once you have the programming for your plugin done, another consideration is internationalization. Internationalization, often abbreviated as i18n, is the process of setting up software so that it can be localized; localization, or l10n, is the process of translating text displayed by the software into different languages. WordPress uses the gettext libraries and tools for i18n.

It is highly recommended that you internationalize your plugin, so that users from different countries can localize it.

Translatable Strings

In order to make a string translatable, you have to just wrap the original string in a __() function call. If your code should echo the string to the browser, use the _e() function instead. As you might have noticed, we've already done that in our plugin.

Text Domains

A text domain is a unique identifier, which makes sure WordPress can distinguish between all loaded translations. Using the basename of your plugin is always a good choice. You can load the plugin's translated strings by calling the load_plugin_textdomain() function, which we've already done in the first part of our tutorial.

PO Files

Now, we need to make a .po file for translators. To do this, we'll use the Poedit translation software. Once you've downloaded it, click File -> New Catalog... to setup a new catalog. A new window should open up. Go to the Project info tab and enter Avatar Manager as the project name.

Poedits Project info tab under the Settings windowPoedits Project info tab under the Settings windowPoedits Project info tab under the Settings window
Poedit's Project info tab under the Settings window

On the Paths tab, let’s leave the base path as . which refers to the directory in which the catalog is.

Poedits Paths tab under the Settings windowPoedits Paths tab under the Settings windowPoedits Paths tab under the Settings window
Poedit's Paths tab under the Settings window

Next, go to the Keywords tab. Remove all the items there, and add in these keywords: __, _e, _n and _x.

Poedits Keywords tab under the Settings windowPoedits Keywords tab under the Settings windowPoedits Keywords tab under the Settings window
Poedit's Keywords tab under the Settings window

Press OK and save the file as avatar-manager/languages/avatar-manager-default.po. Now, the file is ready for translation.

Poedits main windowPoedits main windowPoedits main window
Poedit's main window

Translate all the strings you want and then save the file as avatar-manager/languages/avatar-manager-{locale}.po. The locale is the language code and/or country code you defined in the constant WPLANG in the file wp-config.php.

MO Files

A .mo file is a binary file which contains all the original strings and their translations in a format suitable for fast translation extraction. The conversion is done automatically if you go to Edit -> Preferences -> Editor and check Automatically compile .mo file on save.


Step 10. Releasing and Promoting a Plugin

This section goes through the steps for taking a plugin that you've created and getting it distributed widely.

Submitting to the WordPress Plugin Directory

The fastest, easiest and best way to get your plugin out there is to upload your plugin to the WordPress Plugin Directory. For more details about submitting your plugin see the about page or skip straight to the plugin submission page.

Promoting and Documenting Your Plugin

To submit and promote your plugin to the WordPress Community, first create a page for the plugin on your site with complete and well written instructions. Include a link to this explanation page in the plugin's header, so people can easily check for updates and more information and help.

If you choose to submit your plugin to the WordPress Plugin Directory, also make this information as clear as possible so they can categorize and help others understand the usage of your plugin. You also need to create a readme.txt file in a standard format, and include it with your plugin.


Conclusion

This closes our tutorial; now, we have a fully working plugin and learned some practical tips and tricks about WordPress plugin development. The idea behind this plugin started as a feature requested in WordPress core; I would love to hear your thoughts about it. Does it improve the current workflow? Would you find a similar approach useful but on managing Gravatar images right from your profile screen?

As a bonus, the Avatar Manager plugin is also available on WordPress Plugin Directory and GitHub. Check it out to stay up-to-date with the latest releases. Thanks for reading!


References

  • WordPress Coding Standards - General information about coding standards for WordPress development.
  • Writing a Plugin - Best starting place for learning about how to develop WordPress plugins.
  • Plugin API - Description of how to use action and filter hooks in your WordPress plugin, and core functions that plugins can override.
  • Function Reference - An article with many of the core WordPress functions useful to plugin and theme developers; lists most of the core functions, excluding Template Tags.
  • I18n for WordPress Developers - Internationalization, including a section on how to internationalize your plugin.
  • Plugin Submission and Promotion - Once you have written your plugin, here are some hints on distributing it widely.

External Links

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.