Self-Host WordPress “Google Fonts”

Self-Host WordPress “Google Fonts”

Remember, when I discussed removing Google Fonts from a WordPress theme? This time around, we’ll be re-adding the very same webfonts, yet serve them from our own web server instead of Google’s!

Of note. Below steps are sort of WordPress-specific, but remember: you don’t need Fonts Degooglifier, or WordPress, to start serving your own web fonts. (It really is as simple as having the font files available online, then referring to them in your CSS.)

Removing the call to Google’s font-loading service doesn’t mean we can’t use web fonts anymore. In fact, we can simply add a fonts stylesheet of our own, again using wp_enqueue_style(). We can even reload the very same fonts we previously disabled, but host them on our own domain instead.

Fetching the Font Files

Fonts Degooglifier is a utility that helps download the necessary font files for you, but most of them—they’re open-source, after all—can easily be found elsewhere, too. (You may want to convert—e.g., using an online converter—downloaded TTF files to the newer WOFF2, format, too, for maximum performance and compatibility. For brevity’s sake, I’ll be skipping this step.)

Twenty Seventeen uses four weights, both italic and regular, of Libre Franklin. That’s eight font files in total. Well, feeding its Google Fonts URL to Fonts Degooglifier …

./degooglify.sh https://fonts.googleapis.com/css?family=Libre+Franklin%3A300%2C300i%2C400%2C400i%2C600%2C600i%2C800%2C800i&subset=latin%2Clatin-ext

… results in it downloading eight TrueType font files into a fonts folder and generating a file aptly named Libre-Franklin%3A300%2C300i%2C400%2C400i%2C600%2C600i%2C800%2C800i__subset-latin%2Clatin-ext.degooglified.css. (Let’s rename that to fonts.css, shall we?)

Updating Our Child Theme

Assuming we’ve put the correct TTF files into wp-content/themes/twentyseventeen-child/fonts, we can now simply drop fonts.css into our child theme’s main folder and load it using another early wp_enqueue_style() call:

<?php
add_action( 'wp_enqueue_scripts', function() {
  // Tell WordPress to load our fonts stylesheet instead of Google's.
  wp_enqueue_style( 'twentyseventeen-fonts', get_stylesheet_directory_uri() . '/fonts.css' );

  // Then load our parent theme's styles.
  wp_enqueue_style( 'twentyseventeen-style', get_template_directory_uri() . '/style.css', array( 'twentyseventeen-child-fonts' ) );
}, 9 ); // A rather low prio.

Note: this time, don’t go and add another wp_dequeue_style(). (We wouldn’t want to prevent loading our freshly registered stylesheet.)