Skip to content

Add Google Fonts to WordPress

When using Google Fonts with WordPress, you should NOT use @import, nor just place the HTML in the header. Instead use a function and enqueue them.

First, create a function which sets up the Google Fonts…what’s more is this function also allows the fonts to be translated.

function grd_register_google_fonts() {

	$fonts_url = '';

	/**
	 * Translators: If there are characters in your language that are not
	 * supported by the following, translate this to 'off'. Do not translate
	 * into your own language.
	 */
	$roboto    = esc_html_x( 'on', 'Roboto font: on or off', '_s' );
	$open_sans = esc_html_x( 'on', 'Open Sans font: on or off', '_s' );

	if ( 'off' !== $roboto || 'off' !== $open_sans ) {
		$font_families = array();

		if ( 'off' !== $roboto ) {
			$font_families[] = 'Roboto:400,700';
		}

		if ( 'off' !== $open_sans ) {
			$font_families[] = 'Open Sans:400,300,700';
		}

		$query_args = array(
			'family' => rawurlencode( implode( '|', $font_families ) ),
		);

		$fonts_url = add_query_arg( $query_args, '//fonts.googleapis.com/css' );
	}

	return $fonts_url;
}

Finally, enqueue the Google Fonts:

function grd_enqueue_google_fonts() {
    wp_enqueue_style( 'theme-slug-fonts', grd_register_google_fonts(), array(), null );
}
add_action( 'wp_enqueue_scripts', 'grd_enqueue_google_fonts' );

If you want, you can also add the Google Fonts to the WordPress editor:

function grd_editor_styles() {
    add_editor_style( array( 'editor-style.css', grd_register_google_fonts() ) );
}
add_action( 'after_setup_theme', 'grd_editor_styles' );

About Greg Rickaby

Director of Engineering @WebDevStudios / Author & Tech Editor @ForDummies / @WordPress Contributor / @gatsbyjs Maintainer / Follow Greg on Twitter

8 Comments

  1. Dave Kuhar on May 30, 2014 at 16:25

    Hey Greg, can you explain what’s going on in your code? For instance, what’s with the is_ssl part?

    • Greg Rickaby on May 30, 2014 at 16:39

      Sure, I just updated the gist with some more inline comments

      • Dave Kuhar on May 30, 2014 at 17:21

        Oh, cool…and thanks! Now I’m off to update a few sites…



  2. Antonio Gallo on June 2, 2014 at 16:14

    is it possible to skip $protocol and just use //fonts.googleapis.com/css ?

    • Greg Rickaby on June 2, 2014 at 16:17

      I don’t see why not. I know dropping protocol support is a trend (which I’m a big fan of) so, give it a try and let me know!

  3. Jason Hobbs, LLC (@jasonhobbsllc) on July 17, 2014 at 08:49

    Hey Greg, would you recommend this setup, without the $protocol to enqueue Typekit fonts?

    • Greg Rickaby on July 22, 2014 at 13:21

      Yes, I would. In fact I’m thinking of deleting it from the snippet.

  4. Peter on February 9, 2015 at 17:52

    Thank you so much for this! As a new tweaker of child themes I was going crazy due to all the bad examples you mention.
    /peter

Leave a Comment