Using WordPress ‘do_favicon()’ PHP function

The do_favicon() WordPress PHP function displays the contents of the favicon.ico file. The favicon.ico file is used by web browsers to show a small icon next to your site’s URL or in the tab of your browser.

Usage

To use the do_favicon() function, you simply call it without any parameters. Here’s an example:

do_favicon();

This will output the content of your favicon.ico file.

Parameters

  • This function does not accept any parameters.

More information

See WordPress Developer Resources: do_favicon()

The do_favicon() function was introduced in WordPress version 4.3. As of the latest version, this function is not deprecated. For source code details and related functions, please visit the official WordPress Developer Resources link provided above.

Examples

Displaying Favicon in Header

In your theme’s header.php file, you can call the do_favicon() function to display your site’s favicon.

<head>
  ...
  do_favicon();
  ...
</head>

This code will display the favicon of your site in the tab of your web browser.

Checking if Favicon Exists

Before calling the do_favicon() function, you may want to check if a favicon file exists. Here’s how you can do it:

if ( file_exists( get_stylesheet_directory() . '/favicon.ico' ) ) {
  do_favicon();
}

This code checks if a favicon.ico file exists in your current theme’s directory. If it does, it calls the do_favicon() function to display it.

Using a Different Favicon File

If you want to use a different favicon file instead of the default favicon.ico, you can override the do_favicon() function in your theme’s functions.php file:

function do_favicon() {
  echo '<link rel="icon" href="' . get_stylesheet_directory_uri() . '/my-favicon.png">';
}

This code will display the my-favicon.png file as your site’s favicon instead of the default favicon.ico.

Changing Favicon Based on User Role

You can use the do_favicon() function to display different favicons based on the user’s role:

function do_favicon() {
  if ( current_user_can('administrator') ) {
    echo '<link rel="icon" href="' . get_stylesheet_directory_uri() . '/admin-favicon.ico">';
  } else {
    echo '<link rel="icon" href="' . get_stylesheet_directory_uri() . '/user-favicon.ico">';
  }
}

This code will display a different favicon for administrators and users.

Changing Favicon Based on Page

You can also change the favicon based on the current page:

function do_favicon() {
  if ( is_front_page() ) {
    echo '<link rel="icon" href="' . get_stylesheet_directory_uri() . '/home-favicon.ico">';
  } elseif ( is_single() ) {
    echo '<link rel="icon" href="' . get_stylesheet_directory_uri() . '/post-favicon.ico">';
  } else {
    echo '<link rel="icon" href="' . get_stylesheet_directory_uri() . '/default-favicon.ico">';
  }
}

This code will display different favicons for the home page, single post pages, and all other pages.