The Right Way to Add Google Fonts to Your WordPress Theme’s Header

Since WordPress version 2.1.0, theme developers have been using the wp_enqueue_script() function to add scripts to their theme’s headers, instead of hardcoding them in the header.php template file. In version 2.6.0, a similar function for stylesheets, called wp_enqueue_style(), was introduced.

The WordPress Enqueuing System

Together, the wp_enqueue_script() and wp_enqueue_style() functions represent the WordPress enqueuing system, which enables developers to load CSS stylesheets and JavaScript scripts into their custom themes in a programmable way.

The WordPress enqueuing system also allows developers to use the JavaScript libraries that come bundled with any WordPress installation (for e.g., jQuery). This helps to avoid conflicts with plugins, such as having your theme and three plugins load multiple instances of jQuery into your theme.

How to Enqueue Google Fonts in WordPress

This means that there’s a ‘right’ way for WordPress developers to include Google Fonts (or any other web font, for that matter) in their themes’ <head> sections — and it’s not to hardcode it in the theme’s header.php template file.

In a post titled ‘Adding Custom Google Fonts to WordPress with Enqueue’, WPMU DEV have suggested a neat and versatile function for doing so:


<?php 

// This is the 'right' way to enqueue Google Fonts according to the WordPress Codex. 
// Just modify the family and subset arguments of the google_fonts function to your font. 
// Then paste this in your theme's functions.php file or add it to your site-specific plugin. 

function google_fonts() { $query_args = array( 'family' => 'Open+Sans:400,700|Oswald:700',
		'subset' => 'latin,latin-ext',
	);
	wp_enqueue_style( 'google_fonts', add_query_arg( $query_args, "//fonts.googleapis.com/css" ), array(), null );
            }
add_action('wp_enqueue_scripts', 'google_fonts');

?>

Copy and paste this snippet into your theme’s functions.php file. To enqueue the right fonts, edit the font family and subsets in the ‘family’ => method.

Leave a Reply

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