Guide: Self-hosted Google fonts

There are many reasons to self-host Google Fonts. For me, the privacy-aspect is most important. Thanks to Acorn v2.x and spatie/laravel-google-fonts, self-hosting Google Fonts is a breeze.

1. Install spatie/laravel-google-fonts

composer require spatie/laravel-google-fonts

2. Add serviceprovider in themename/config/app.php (providers section).
Spatie\GoogleFonts\GoogleFontsServiceProvider::class,

If the app.php file is not present in the config directory, you need to publish it:
wp acorn vendor:publish --tag=acorn

3. Publish spatie/laravel-google-fonts config files:
wp acorn vendor:publish --tag=google-fonts-config

4. Update themename/config/google-fonts.php

  • Replace/add fonts in the fonts-section
  • Change disk to ‘local’, so fonts are written to WP_CONTENT_DIR
  • Change fallback to env('WP_ENV') == 'production', or whatever way you can check this is a production website

5. Add the stylesheet to your head section (in themename/index.php, <head> section):

<?php echo app(Spatie\GoogleFonts\GoogleFonts::class)->load()->toHtml(); ?>

spatie/laravel-google-fonts provides a directive for adding this CSS, but as index.php is a regular PHP file, directives won’t work in this file.

That’s about it. First time you load your website, it will fetch the fonts and place theme in /app/fonts. You can fetch the fonts from command line with following command: wp acorn google-fonts:fetch

Github: Manage self-hosted Google Fonts in Laravel apps

16 Likes

Nice howto for latest Sage 10, thanks!

My only gripe with spatie/laravel-google-fonts is that it doesn’t add preloading

Their issue tracker is closed sadly, so I can’t add an improvement proposal.

2 Likes

The idea of spatie’s google fonts is that you won’t need to use the font link client side or google domain, so you don’t need the preconnect. It connects and downloads on the server the first time you request it. And keeps it up to date.

I wonder if it can be added when the fallback is used and only when it is used though.

2 Likes

In case you need the fonts in the block editor:

add_action('admin_head', function () {
    echo app(\Spatie\GoogleFonts\GoogleFonts::class)->load()->toHtml();
});
2 Likes

I always use the ‘Google webfont helper’ which allows you to download the fonts and use them in your theme folder. That seems a bit easier than using PHP for this.

1 Like