Add Google Fonts to WordPress

There are so many terrible examples on adding Google Fonts to WordPress.

You should NOT use @import, nor just place the HTML in the header. Instead use a function and enqueue it!

/**
 * Enqueue Google Fonts.
 */
function custom_enqueue_google_font() {

$query_args = array(
 'family' => 'Open+Sans:400,300,700|Roboto:400,700|Gloria+Hallelujah'
 );

 wp_register_style( 'google-fonts', add_query_arg( $query_args, "//fonts.googleapis.com/css" ), array(), null );
 wp_enqueue_style( 'google-fonts' );

}
add_action( 'wp_enqueue_scripts', 'custom_enqueue_google_font' );

Update: It’s been brought to  my attention that the above function isn’t translatable and can’t be easily extended into editor styles. Furthermore, if you’re submitting a theme to WordPress.org you will need to enqueue Google Fonts in accordance with Theme Shaper’s post on adding Google Fonts.

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 4:25 pm

    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 4:39 pm

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

      • Dave Kuhar on May 30, 2014 at 5:21 pm

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



  2. Antonio Gallo on June 2, 2014 at 4:14 pm

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

    • Greg Rickaby on June 2, 2014 at 4:17 pm

      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 8:49 am

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

    • Greg Rickaby on July 22, 2014 at 1:21 pm

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

  4. Peter on February 9, 2015 at 5:52 pm

    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