wp_resource_hints()
Prints resource hints to browsers for pre-fetching, pre-rendering and pre-connecting to web sites.
Gives hints to browsers to prefetch specific pages or render them in the background, to perform DNS lookups or to begin the connection handshake (DNS, TCP, TLS) in the background.
These performance improving indicators work by using <link rel"…">.
Hooks from the function
Return
null
. Nothing (null).
Usage
wp_resource_hints();
Examples
#1 How to properly disable DNS prefetch for s.w.org (emoji)
Since version 4.6.0 there is a special hook that allows you to disable prefetch for s.w.org (emoji):
// Removing DNS prefetch for WP Emoji from the header add_filter( 'emoji_svg_url', '__return_false' );
#2 Add prefetch instructions for custom URLs (domains)
Suppose we need to forcibly add browser instructions for certain URLs or domains. Let's use hook wp_resource_hints:
add_filter( 'wp_resource_hints', 'wp_kama_resource_hints_filter', 10, 2 ); /** * Function for `wp_resource_hints` filter-hook. * * @param array $urls Array of resources and their attributes, or URLs to print for resource hints. * @param string $relation_type The relation type the URLs are printed for, e.g. 'preconnect' or 'prerender'. * * @return array */ function wp_kama_resource_hints_filter( $urls, $relation_type ){ if( 'dns-prefetch' === $relation_type ){ $urls[] = 'https://dnsprefetch.com/foo'; } if( 'preconnect' === $relation_type ){ $urls[] = 'https://preconnect.com/some'; } if( 'prefetch' === $relation_type ){ $urls[] = 'https://prefetch.com/some'; $urls[] = '//prefetch-no-proto.com/some'; $urls[] = [ 'href' => 'https://prerender-array.com/some.css', 'as' => 'style', 'crossorigin' => 'use-credentials', 'pr' => 12.5, 'type' => 'text/css', ]; } if( 'prerender' === $relation_type ){ $urls[] = 'https://prerender.com/some'; } return $urls; }
Get the following in the HEAD part of the HTML:
<link rel='dns-prefetch' href='//dnsprefetch.com' /> <link rel='preconnect' href='https://preconnect.com' /> <link rel='prefetch' href='https://prefetch.com/some' /> <link rel='prefetch' href='//prefetch-no-proto.com/some' /> <link href='https://prerender-array.com/some.css' as='style' crossorigin='use-credentials' pr='12.5' type='text/css' rel='prefetch' /> <link rel='prerender' href='https://prerender.com/some' />
#3 Removing dns-prefetch
rule from HTML HEAD
Suppose we have dns-prefetch
rules in the HTML document <head> which we don't need and we need to remove them. For example, we need to delete the following domain external.com
:
add_filter( 'wp_resource_hints', function( $urls ) { foreach ( $urls as $key => $url ) { if ( str_contains( $url, 'external.com' ) ) { unset( $urls[ $key ] ); } } return $urls; } );
Changelog
Since 4.6.0 | Introduced. |