How to Display Gravatar Image as the Favicon in WordPress

Home » Snippets » How to Display Gravatar Image as the Favicon in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Do you want to have a unique and dynamic favicon for your website? By default, WordPress uses a generic favicon for all websites. However, if you want to add a personal touch and showcase your website’s branding, you can change the favicon to display your Gravatar image. In this article, we will guide you through the process of replacing the default favicon with your own Gravatar image, adding a stylish and personalized touch to your website.

					function wpturbo_display_gravatar_favicon() {
    $email = get_option('admin_email');
    $hash = md5(strtolower(trim($email)));
    ?>
    <link rel="icon" href="//www.gravatar.com/avatar/<?php echo $hash; ?>?s=16&d=mm" sizes="16x16">
    <?php
}
add_action('wp_head', 'wpturbo_display_gravatar_favicon');
				

The code snippet above shows a function called wpturbo_display_gravatar_favicon() that is responsible for displaying the Gravatar image as the favicon on a WordPress website.

First, we retrieve the email address of the site administrator by using the get_option('admin_email') function and assign it to the variable $email. This email address will be used to generate the hash for the Gravatar URL.

We then use the md5(strtolower(trim($email))) function to convert the email address to its MD5 hash. The md5() function creates a 32-character hexadecimal number representing the given string. In this case, we convert the email address to lowercase and remove any leading or trailing whitespace before generating the hash.

Next, we include the favicon link tag in the page's head section. The href attribute of the link tag is set to "//www.gravatar.com/avatar/<?php echo $hash; ?>?s=16&d=mm". This URL points to the Gravatar image associated with the MD5 hash of the email address. The s=16 parameter sets the size of the image to 16 pixels, and the d=mm parameter specifies that the default image should be displayed if no Gravatar image is found for the given email address.

By including this link tag in the head section of the WordPress website, the Gravatar image will be displayed as the favicon. The sizes attribute specifies that the favicon is 16x16 pixels in size, which is the standard size for favicons.

Finally, we use the add_action() function to hook the wpturbo_display_gravatar_favicon() function into the wp_head action. This ensures that the function is executed when the WordPress website's head section is rendered.

In summary, this code snippet allows you to display the Gravatar image associated with the site administrator's email address as the favicon on a WordPress website.

Register an account to save your snippets or go Pro to get more features.