Automatically generate Google Fonts link.

Useful if you are making a customizable skin, or if you allow users to set font preferences in their account settings.

Of course, the basic way you include google fonts on your page is like this:

HTML (preconnects are technically optional):

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="FONT SPECIFIC LINK" rel="stylesheet">

Or, CSS Include:

@import url('FONT SPECIFIC LINK');

So how to generate that link from an array of font names?

Well, here it is in javascript, which can be used either in node.js or in browser-side javascript with a bit of extra code to create a <link> dom element on the fly:

const googleFonts = { 
  /* 'Font Name': [] //default weight only
   * or 'Font Name': [list normal weights]
   * or 'Font Name': [[list normal weights], [list italic weights]] */
  'Poiret One' => [],
  'Merriweather' => [[400, 700, 900], [400, 700, 900]],
  'Roboto' => [300, 400],
} 

let googleFontURL = "https://fonts.googleapis.com/css2?"; 

Object.keys(googleFonts).forEach((key) => { 
  element = googleFonts[key];
  if (element.length == 0) googleFontURL += `family=${key}&`; 
  else if (!Array.isArray(element[0])) googleFontURL += `family=${key}:wgt@${element.join(';')}&`; 
  else if (element[0].length == 0) googleFontURL += `family=${key}:ital,wgt@01,${element[1].join(';0,')}&`; 
  else googleFontURL += `family=${key}:ital,wgt@0,${element[0].join(';0,')};1,${element[1].join(';0,')}&`; }); 

googleFontURL += "display=swap";

And in PHP (for WordPress templates, for example):

$googleFonts = [
  /* 'Font Name': [] //default weight only
   * or 'Font Name': [list normal weights]
   * or 'Font Name': [[list normal weights], [list italic weights]] */
  'Poiret One' => [],
  'Merriweather' => [[400, 700, 900], [400, 700, 900]],
  'Roboto' => [300, 400],
];

function google_webfonts_link($googleFonts)
{
  $googleFontURL = "https://fonts.googleapis.com/css2?";
  foreach ($googleFonts as $key => $sizes) {
    if (!is_array($sizes)) { 
      //assume someone just put in a plain array of font names
      $googleFontURL .= "family=" . str_replace(" ", "+", $sizes) . "&"; 
    } 
    else if (count($sizes) == 0) {
      $googleFontURL .= "family=" . str_replace(" ", "+", $key) . "&";
    } else if (!is_array($sizes[0])) {
      $googleFontURL .= "family=" . str_replace(" ", "+", $key) . ":wgt@" . implode(';', $sizes) . "&";
    } else if (is_array($sizes[0]) && count($sizes[0]) == 0) {
      $googleFontURL .= "family=" . str_replace(" ", "+", $key) . ":ital,wgt@01," . implode($sizes[1], ";0,") . "&";
    } else {
      $googleFontURL .= "family=" . str_replace(" ", "+", $key) . ":ital,wgt@0," . implode(';0,', $sizes[0]) . ";1," . implode(';1,', $sizes[1]) . "&";
    }
  }
  $googleFontURL .= "display=swap";
  return $googleFontURL;
}

(Yeah, I could use string interpolation, but my php syntax highlighter doesn’t handle {..} style interpolation. That’s what you get for using free software.)

WordPress note: php will strip out duplicate query string parameters once it knows it’s a url, so adding a version to wp_enque_styles will ruin your google fonts link.

Have a question?

Your email address will not be published. Required fields are marked *