Change dns-prefetch to preconnect for external enqueued resources

There’s a filter, wp_resource_hints, but it only filters each “relation type” (i.e. preconnect, dns-prefetch, etc.) individually, rather than the whole $hints array in your question. However, you could use the filter to empty the array for dns-prefetch and add wp_resource_hints_scripts_styles() to the preconnect array, like this:

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

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

        return $urls;
    },
    0,
    2
);

Note that I used a priority of 0. This is to make sure that any URLs that were manually added to dns-prefetch by another plugin or theme aren’t accidentally removed from all the lists, since we’re only able to move the URLs from wp_dependencies_unique_hosts().

Leave a Comment