Skip to main content
Menu
Home > Blog > WordPress Development

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', 'https://fonts.googleapis.com/css2?family=Nunito:wght@800&family=Open+Sans:ital,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='https://fonts.googleapis.com/css2?family=Open+Sans%3Aital%2Cwght%400%2C400%3B0%2C700%3B1%2C400%3B1%2C700&display=swap&ver=5.4.1' 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', 'https://fonts.googleapis.com/css2?family=Nunito:wght@800&family=Open+Sans:ital,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

Related Articles

Copy link