Change dns-prefetch to preconnect with correct protocol

I have this function in my functions.php file:

function dns_prefetch_to_preconnect( $urls, $relation_type ) {
    if ( 'dns-prefetch' === $relation_type ) {
        $urls = [];
    }

    if ( 'preconnect' === $relation_type ) {
        $urls = wp_dependencies_unique_hosts();
    }

    return $urls;
}
add_filter( 'wp_resource_hints', 'dns_prefetch_to_preconnect', 0, 2 );

It takes the URLs defined in wp_dependencies_unique_hosts() – which WordPress by default assigns to the dns-prefetch link tag – and reassigns them to the preconnect link tag. The function was provided to me here:

Change dns-prefetch to preconnect for external enqueued resources

However, this function isn’t working entirely correctly. It adds the preconnect URLs using http instead of https.

Example: when I’m not using the above function, WordPress adds this link to my header:

<link rel="dns-prefetch" href="https://fonts.googleapis.com" />

And when I enable the above function, it replaces that link with this link:

<link rel="preconnect" href="http://fonts.googleapis.com" />

The problem, of course, is that it should be https, not http.

Can someone help me modify my function so that it gives me https links?

2 Answers
2

The problem is not that the function you’re using adds http:, the problem is it adds no URL schema at all!

As a result, WP needs to add a URL schema to turn the host into a URL, and so it uses http://. It has no way of knowing what the original was, or if the host supports HTTPS, so http:// is the safe bet.

If however you passed the array with URL schema added, it would be passed through without issue.

Something like this may do the trick:

$hosts = wp_dependencies_unique_hosts();
$urls = array_map( function( $host ) {
    return set_url_scheme( $host, 'https' );
}, $hosts );

In the longrun though, it would be better to get the actual URLs and distill the host URL out of them, rather than relying on wp_dependencies_unique_hosts if you wanted to preserve the mixture of http and https

Leave a Comment