Skip to main content

Making Google Fonts New URL Compatible with wp_enqueue_script

May 8th, 2020

Google Fonts changed their embed link structure recently and I noticed odd behavior when generating an embed URL with multiple families and utilizing it with wp_enqueue_script. My old script loading function included a Google Fonts call similar to this:

wp_register_style('googleFonts', ',wght@0,400;0,700;1,400;1,700&display=swap');
wp_enqueue_style( 'googleFonts');

However, after Google changed its font embedding URL structure, something funny was happening when using it: it was stripping out everything but the last font in the URL. So the above on the front-end would instead be:

<link rel='stylesheet' id='googleFonts-css'  href='' type='text/css' media='all' />

As you can see, the first font family in my PHP call, Nunito, is nowhere to be found. Apparently, it’s a conflict with the new Google Fonts URL structure and how the version number is appended to the link if left in its default state. In order to prevent this from happening, the function had to be adjusted to null out the version parameter and instead look like this:

wp_register_style('googleFonts', ',wght@0,400;0,700;1,400;1,700&display=swap', array(), null);
wp_enqueue_style( 'googleFonts');

Now, there is a WordPress core ticket that flags this issue and notes the solution so there may be an adjustment soon in place where this won’t be required. But until then, the Google Fonts URL structure for multiple font families conflicts with how the version is appended to the URL so it’s important to include a null parameter for the version to get it to spit out the Google Fonts URL with all font families included.

If you’re having issues with fonts being stripped out of your Google Fonts embed URL when using wp_enqueue_script, the above solution should hopefully remedy it for you.

MORE: WordPress Development, WordPress Tutorials

Related Articles