1

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="/fonts/custom-font-folder/CustomFontFile.woff2" as="font" type="font/woff2" crossorigin="anonymous">

Thank you in advance.

  • Try updating your question with at least some effort using the enqueue style function. – Jesús Franco Nov 29 '19 at 13:04
0

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', '/fonts/custom-font-folder/CustomFontFile.woff2', array(), null);

}

add_filter('style_loader_tag', 'my_style_loader_tag_filter');

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" />');

  }

  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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.