Skip to content

Instantly share code, notes, and snippets.

@brianleejackson
Created September 23, 2020 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianleejackson/908d0e7908279e81ac72e84fb76afe50 to your computer and use it in GitHub Desktop.
Save brianleejackson/908d0e7908279e81ac72e84fb76afe50 to your computer and use it in GitHub Desktop.
Enqueue and preload a font in WordPress
function enqueue_font_preload() {
wp_enqueue_style('example-font-handle', 'https://domain.com/wp-content/font-file.woff2', array(), null);
}
add_action('wp_enqueue_scripts', 'enqueue_font_preload');
function style_loader_tag_filter_preload($html, $handle) {
if($handle === 'example-font-handle') {
$new_html = str_replace("text/css", "font/woff2", $html);
return str_replace("rel='stylesheet'", "rel='preload' as='font' crossorigin='anonymous'", $new_html);
}
return $html;
}
add_filter('style_loader_tag', 'style_loader_tag_filter_preload', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment