Using WordPress ‘do_favicon’ PHP action

The do_favicon WordPress PHP action is fired when the template loader determines a favicon.ico request.

Usage

add_action('do_favicon', 'your_custom_function');
function your_custom_function() {
    // your custom code here
}

Parameters

  • None

More information

See WordPress Developer Resources: do_favicon

Examples

Add a custom favicon to your site

This example adds a custom favicon to your WordPress site by using the do_favicon action.

add_action('do_favicon', 'my_custom_favicon');
function my_custom_favicon() {
    $favicon_url = get_stylesheet_directory_uri() . '/images/favicon.ico';
    echo '<link rel="shortcut icon" href="' . esc_url($favicon_url) . '" />';
}

Load different favicons based on user role

This example loads different favicons for different user roles using the do_favicon action.

add_action('do_favicon', 'load_favicon_based_on_user_role');
function load_favicon_based_on_user_role() {
    $user = wp_get_current_user();
    $favicon_url = '';

    if (in_array('administrator', (array) $user->roles)) {
        $favicon_url = get_stylesheet_directory_uri() . '/images/favicon_admin.ico';
    } else {
        $favicon_url = get_stylesheet_directory_uri() . '/images/favicon_user.ico';
    }

    echo '<link rel="shortcut icon" href="' . esc_url($favicon_url) . '" />';
}

Modify the favicon for a specific custom post type

This example shows how to change the favicon for a specific custom post type using the do_favicon action.

add_action('do_favicon', 'change_favicon_for_custom_post_type');
function change_favicon_for_custom_post_type() {
    if (is_singular('your_custom_post_type')) {
        $favicon_url = get_stylesheet_directory_uri() . '/images/favicon_custom_post_type.ico';
        echo '<link rel="shortcut icon" href="' . esc_url($favicon_url) . '" />';
    }
}

Add a dynamic favicon based on the site’s primary color

This example demonstrates how to create a dynamic favicon based on your site’s primary color using the do_favicon action.

add_action('do_favicon', 'dynamic_favicon_based_on_primary_color');
function dynamic_favicon_based_on_primary_color() {
    $primary_color = get_theme_mod('primary_color', '#000000');
    $favicon_url = 'https://fakeimg.pl/16x16/' . ltrim($primary_color, '#') . '/?text=%20';
    echo '<link rel="shortcut icon" href="' . esc_url($favicon_url) . '" />';
}

Add a favicon only on the homepage

This example adds a favicon to your WordPress site only on the homepage using the do_favicon action.

add_action('do_favicon', 'add_favicon_to_homepage');
function add_favicon_to_homepage() {
    if (is_front_page()) {
        $favicon_url = get_stylesheet_directory_uri() . '/images/favicon_home.ico';
        echo '<link rel="shortcut icon" href="' . esc_url($favicon_url) . '" />';
    }
}