WP-Mix

A fresh mix of code snippets and tutorials

The Right Way to Include Google Fonts in WordPress

This tutorial explains the right (and wrong) way to include (aka enqueue) Google Fonts in your WordPress theme.

The WRONG way to enqueue Google fonts

First let’s look at the wrong way to enqueue Google fonts, then we’ll see how to do it the right way. I see this unsavory technique used in various themes and plugins (including one of my own from a couple of years ago!):

function wrong_way_to_include_google_fonts() {
	echo '<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700">';
}
add_filter('wp_head', 'wrong_way_to_include_google_fonts');

Sure it works, but it is not according to WordPress best practices or WP API, which should be top priority for anyone developing WordPress stuff. This method basically adds the Google Font <link> tag by filtering wp_head. Definitely the wrong way to enqueue Google fonts.

The RIGHT way to enqueue Google fonts

Here is the correct approach, according to the WP API and best practices:

function right_way_to_include_google_fonts() {
	if (!is_admin()) {
		wp_register_style('google', 'https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700', array(), null, 'all');
		wp_enqueue_style('google');
	}
}
add_action('wp_enqueue_scripts', 'right_way_to_include_google_fonts');

Here we are registering the Google Font stylesheet using wp_register_style(), and then enqueueing it with wp_enqueue_style(). This enables us to customize the output of the <link> tag by changing the parameters:

wp_register_style($handle, $src, $deps, $ver, $media);

Learn more about these functions at the WordPress Codex.

References

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress