WP Method `get_theme_file_uri()` Doesn't Seem To Be Working Properly When Used In The Head Section Of A Site

wordpress.stackexchange https://wordpress.stackexchange.com/questions/382694

  •  22-04-2021
  •  | 
  •  

Question

I'm preloading a web font in the head section of a WP custom theme and when I use the full file path it doesn't throw an error and works OK.

When I use the WP function get_theme_file_uri inside the href attribute, it loads the font but shows errors in the console and in Chrome's Lighthouse audit. The code I'm using in the href attribute is:

href="<?php echo get_theme_file_uri('/fonts/alaska.ttf') ?> );"

The file loads all OK but it questions whether I'm suing the as attribute in the console and in Chrome's Lighthouse audit asks if I'm using the crossorigin attribute correctly. I'm am using both of those attributes like this:

<link rel="preload" href="<?php echo get_theme_file_uri('/fonts/alaska.ttf') ?> );" as="font" type="font/ttf" crossorigin="anonymous">

My question is, is there a WP method that can be used in the head section for getting theme files that would be more appropriate than this. For obvious reasons I don't want to be putting the full file path in themes I'm making and then have to change this when a site is uploaded from a localhost environment.

The Error Messages I Get Are:

Console

The resource http://localhost:8888/inset/wp-content/themes/inset/fonts/alaska.ttf%20); was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally.

Chrome Lighthouse Audit

Warnings: A preload <link> was found for "http://localhost:8888/inset/wp-content/themes/inset/fonts/alaska.ttf" but was not used by the browser. Check that you are using the crossorigin attribute properly.

I get these error messages on both the localhost and live site, with no further info/explanation.

Was it helpful?

Solution

You have these characters in the href that shouldn't be there: ); At the end.

href="<?php echo get_theme_file_uri('/fonts/alaska.ttf') ?> );"

It should be

href="<?php echo get_theme_file_uri('/fonts/alaska.ttf'); ?>"
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top