Google fonts enqueue only imports last font family

I am trying to import three google fonts by adding the following to my functions.php file:

function get_google_fonts() {
    wp_enqueue_style( 'get-google-fonts', 'https://fonts.googleapis.com/css2?family=Alata&family=Baloo+Tamma+2&family=Roboto:wght@100&display=swap', false ); 
}

add_action( 'wp_enqueue_scripts', 'get_google_fonts' );

However, WordPress seems to be enqueueing only the last font (here, Roboto) when I view my site.

<link rel="stylesheet" id="get-google-fonts-css" href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap&amp;ver=5.5" type="text/css" media="all">

The site is new and WordPress is just installed. There are no plugins installed yet. What is the reason for this?

EDIT:

I tried splitting up the fonts into separate enqueues as follows and the fonts are all working now:

function get_google_fonts() {
    wp_enqueue_style( 'get-font-1', 'https://fonts.googleapis.com/css2?family=Alata&display=swap', false );
    wp_enqueue_style( 'get-font-2', 'https://fonts.googleapis.com/css2?family=Baloo+Tamma+2&display=swap', false );
    wp_enqueue_style( 'get-font-3', 'https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap', false );
}

add_action( 'wp_enqueue_scripts', 'get_google_fonts' );

But I don’t understand why the single request approach didn’t work.

1 Answer
1

From the wp_enqueue_style() documentation:

$ver
(string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as
a query string for cache busting purposes. If version is set to false,
a version number is automatically added equal to current installed
WordPress version. If set to null, no version is added.

Default value: false

So when the version number is not exactly a null (i.e. $ver !== null), WordPress uses add_query_arg() to add the version number and because the function supports only one instance of the same query string (except for arrays like family[] and foo_bar[]), the previous family queries in the stylesheet URL are removed by add_query_arg().

Therefore, you can either enqueue the font families one per wp_enqueue_style() call (like you’ve tried), or set the $ver to null (and manually add the version number or cache buster query):

wp_enqueue_style( 'get-google-fonts', 'https://fonts.googleapis.com/css2?family=Alata&family=Baloo+Tamma+2&family=Roboto:wght@100&display=swap', array(), null );

Leave a Comment