I just needed to do something like this. I thought modifying <head>
directly didn't sound like the best idea, so I looked at the Wordpress source.
I found that the favicon URL is filtered through the get_site_icon_url
filter (see https://developer.wordpress.org/reference/functions/get_site_icon_url/). In this filter, you can find out what page you're on (for example using the get_current_screen()
function) and then return a different URL.
Here's my code for reference:
function get_custom_favicon( $url, $size, $blog_id ) {
$favicons = array(
'edit-product' => 13975, // attachment ID
'edit-shop_order' => 13974,
);
$screen = get_current_screen();
$screen_id = $screen ? $screen->id : 0;
if ( isset( $favicons[ $screen_id ] ) && ( $image_id = $favicons[ $screen_id ] ) ) {
if ( $size >= 512 ) {
$size_data = 'full';
} else {
$size_data = array( $size, $size );
}
$url = wp_get_attachment_image_url( $image_id, $size_data );
}
return $url;
}
add_filter( 'get_site_icon_url', 'get_custom_favicon', 10, 3 );
The array at the top contains a mapping from the page ID to image attachment ID (which you can get easily from the page URL when you open the image Media in Wordpress). The code within the isset()
if-statement is lifted directly from the WordPress source, so it handles the favicon image in the exact same way.
is_single(123)
that is only true if the post with the ID 123 is currently shown to fine tune what to show.