Add Snippet To Project
The tiny icon that appears in the browser tab next to your website title, called a favicon, is a significant part of your site’s visual identity. Often overlooked, it plays a crucial role in enhancing user experience, brand recognition and even SEO. Would you like to learn how to add this favicon to your WordPress website via a specific function? In this article, we will provide you with a clear, step-by-step guide on how to insert a favicon using a function, aiding you in branding your site down to the smallest details.
function wpturbo_insert_favicon() {
echo '<link rel="shortcut icon" type="image/x-icon" href="' . get_stylesheet_directory_uri() . '/favicon.ico" />';
}
add_action('wp_head', 'wpturbo_insert_favicon');
The code snippet is creating a function named wpturbo_insert_favicon()
, which, when executed, will place a favicon into a WordPress website. A favicon (short for "favorites icon") is a small, iconic image that represents your website. Favicons are most often found in the address bar of your web browser, but they can also be used in lists of bookmarks in web browsers and other places.
Let’s take a closer look at how this function is accomplishing that:
function wpturbo_insert_favicon() {
echo '<link rel="shortcut icon" type="image/x-icon" href="' . get_stylesheet_directory_uri() . '/favicon.ico" />';
}
Inside this function, we encounter an echo
statement, which outputs the string. This string constructs the necessary HTML markup for adding a favicon.
Specifically, we’re creating a link
element, which has a rel
attribute set to "shortcut icon". This tells the browser that the referenced resource is a favicon.
The type
attribute is set to "image/x-icon", which is the standard MIME type for a favicon.
The href
attribute points to the location of the favicon file. Its value is built using the get_stylesheet_directory_uri()
function, which retrieves the URI of the current theme’s directory, concatenated with ‘/favicon.ico’. This means that the code assumes your favicon file is named ‘favicon.ico’ and is located in the root of your theme directory.
In the final line of the snippet, add_action('wp_head', 'wpturbo_insert_favicon');
hooks the function to the wp_head
action, which is run in the header section of your site’s front-end pages. This is where link elements are usually placed, ensuring that the function runs each time a page is loaded and successfully inserts the link to your favicon.
Remember, this function assumes your favicon file is located at the root of your current theme directory. If your favicon file is located somewhere else, make sure to update the href
attribute in the echo statement accordingly.