Enqueue custom font file with rel=”preload”

You could try using the style_loader_tag filter.

add_action('wp_enqueue_scripts', 'my_enqueue_scripts');

function my_enqueue_scripts() {
    wp_enqueue_style('my-style-handle',
        "https://wordpress.stackexchange.com/fonts/custom-font-folder/CustomFontFile.woff2", array(), null);
}

add_filter('style_loader_tag', 'my_style_loader_tag_filter', 10, 2);

function my_style_loader_tag_filter($html, $handle) {
    if ($handle === 'my-style-handle') {
        return str_replace("rel="stylesheet"",
            "rel="preload" as="font" type="font/woff2" crossorigin='anonymous'", $html);
    }
    return $html;
}

Here we’re enqueuing the stylesheet using the normal wp_enqueue_style function. We then capture the output using the filter and replace it’s rel attribute with your updated attributes.

Leave a Comment