Why can’t I enqueue multiple Google Fonts in WordPress functions.php?

Question:

I’m using wp_enqueue_style to enqueue this Google Font file. Here is my code:

wp_enqueue_style( 'google-fonts', 'https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,300;0,400;0,700;1,400&family=Neuton:ital,wght@0,300;0,400;0,700;1,400&display=swap', [] );

This is in my functions.php file.

However, when I view source on my loaded page, the URL for that font file is cut down to: https://fonts.googleapis.com/css2?family=Neuton%3Aital%2Cwght%400%2C300%3B0%2C400%3B0%2C700%3B1%2C400&display=swap&ver=5.3.2

As you can see, the first family param has been removed after being outputted through wp_enqueue_style. Is there a way to fix this without doing anything hacky? I think there may be an outdated way to build the URL for both font families to come through, but I’d rather be able to use what Google now provides. My original URL inside wp_enqueue_style is the URL generated by Google Fonts for me to embed.

Answer:

This actually has to do with PHP and the way it parses query parameters.

https://www.php.net/manual/en/function.parse-str.php

In any case, the current workaround is to pass “null” to the version parameter to have WordPress not add a “ver” to the URL.

wp_enqueue_style( 'google-fonts', 'https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,300;0,400;0,700;1,400&family=Neuton:ital,wght@0,300;0,400;0,700;1,400&display=swap', [], null );

That ending “null” will eliminate the problem, since WordPress won’t try to add any additional parameters to the URL, thus not running it through PHP’s query string handling functions.

This may be addressed more directly in a future WordPress update. However, having no version on these external URLs makes sense regardless.

https://stackoverflow.com/questions/60953810/why-cant-i-enqueue-multiple-google-fonts-in-wordpress-functions-php
  • Categories