I’m using a custom font on my WP site. It is now included with @font-face
css attribute. But I’m wondering if there is any way to wp_enqueue
this file with the attribute rel="preload"
and may be some other attributes. So it looks something like this in browser:
<link rel="preload" href="https://wordpress.stackexchange.com/fonts/custom-font-folder/CustomFontFile.woff2" as="font" type="font/woff2" crossorigin="anonymous">
Thank you in advance.
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.