Adding Google Fonts to WordPress with Enqueue in functions.php

I have frequently added references to the additional CSS and JavaScript files using enqueue within the functions.php file of a WordPress theme.

Where possible I have downloaded fonts for use adding them to the site files. There was a time when Firefox would grumble about such inclusions referenced from another server, not served from the same server as the website page.

On this occasion I looked to take a different approach. The idea being to use the Google font server reference.

How to add Google hosted fonts, or others, to a WordPress theme via the functions.php file?

WordPress manages the inclusion of script files and CSS files by way of the functions wp_enqueue_scripts and wp_enqueue_style.

Taking a simple script and CSS file inclusion:

function add_custom_styles() {


    // Get the theme data


    $the_theme = wp_get_theme();


    wp_enqueue_style( 'theme-styles', get_template_directory_uri().'/css/theme.min.css', array(), $the_theme->get( 'Version' ) );


    wp_enqueue_style( 'fontawesome', get_stylesheet_directory_uri().'/css/fontawesome.min.css', array(), '1.1');

}


add_action( 'wp_enqueue_scripts', 'add_custom_styles' );


Looking to enqueue the Google fonts incorporating the above method of enqueue gives:

function add_custom_fonts() {



	wp_enqueue_style( 'custom-fonts-lato', 'https://fonts.googleapis.com/css?family=Lato:100,100italic,300,300italic,400,400italic,700,700italic,900,900italic', false );



	wp_enqueue_style( 'custom-fonts-poiret-one', 'https://fonts.googleapis.com/css?family=Poiret One:regular', false );


}



add_action( 'wp_enqueue_scripts', 'add_custom_fonts' );


In the above example I have added two of Google’s fonts.

Shown below is the page view source representation of these two added fonts:

<link rel='stylesheet' id='custom-fonts-lato-css'  href='https://fonts.googleapis.com/css?family=Lato%3A100%2C100italic%2C300%2C300italic%2C400%2C400italic%2C700%2C700italic%2C900%2C900italic&ver=4.9.8' type='text/css' media='all' />
<link rel='stylesheet' id='custom-fonts-poiret-one-css'  href='https://fonts.googleapis.com/css?family=Poiret+One%3Aregular&ver=4.9.8' type='text/css' media='all' />

References

WordPress enqueue style codex reference