WordPress Tip: How to Load Google Fonts Over SSL and Non-SSL

Here’s a quick tip for when you load Google fonts in WordPress. If you want the fonts to work over both SSL and non-SSL, you need to use the protocol relative link.

For example, if you’re loading Google fonts from your theme’s functions.php file, you might do it like this:

[php light=”true”]function mytheme_enqueue_styles() {
wp_register_style(‘googleFonts’, ‘http://fonts.googleapis.com/css?family=Copse’);
wp_enqueue_style( ‘googleFonts’);
}[/php]

However, this method breaks over HTTPS, which means that all your fancy custom fonts won’t work and the browser’s default will be loaded instead, ie. Times New Roman.

Removing the “http” protocol from the link will allow the visitor’s browser to determine the correct protocol to load.

[php light=”true”]function mytheme_enqueue_styles() {
wp_register_style(‘googleFonts’, ‘//fonts.googleapis.com/css?family=Copse’);
wp_enqueue_style( ‘googleFonts’);
}[/php]

There are many tutorials that claim to show you “The Right Way to Load Google Fonts in WordPress,” but most of them don’t use the protocol relative link. If you’ve ever forced SSL on pages then you know that all of your assets, including images, CSS, JS, fonts, etc., will be broken unless they are loaded via HTTPS. You should use the protocol relative links wherever possible when the assets or third-party links are available via both HTTP and HTTPS.

6

6 responses to “WordPress Tip: How to Load Google Fonts Over SSL and Non-SSL”

  1. A good practice here is to make sure you prefix your script handle with your theme or plugin name. For example, instead of googleFonts use theme-slug-googleFonts; this will help to avoid potential conflicts with other themes or plugins that have also tried to take googleFonts for their own use.

  2. Great!

    This script works very good! but when the user enters the site from any browser, without warning (only the symbol appears next to the URL bar), notice to allow loading insecure content. then until the user does not allow upload content, the fonts remain in Times New Roman :(

    Any way to fix this and load the Google Fonts directly without permission browser?

    Thank you very much!

Newsletter

Subscribe Via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.