How WordPress default themes add Google Fonts

Category:

I spent some time diving into Twenty Seventeen in preparation to develop a theme for the directory. I was curious as to how the developers of a very popular theme would enqueue a Google Font. I am no stranger to using a @import tag in the stylesheet, but I assumed there had to be a more sustainable solution. What I found was a thoughtful way of adding a font which I have digested into a gist below.

Handling your Google Fonts in this manner allows translators of your theme to disregard a font that may hinder the translation.

/**
 * Register custom fonts.
 */
function themeslug_fonts_url() {
	$fonts_url = '';
	$fonts     = array();
	$subsets   = 'latin,latin-ext';

	/*
	 * Translators: If there are characters in your language that are not supported
	 * by Oswald, translate this to 'off'. Do not translate into your own language.
	 */
	if ( 'off' !== _x( 'on', 'Oswald font: on or off', 'themeslug' ) ) {
		$fonts[] = 'Oswald:400,700';
	}

	/*
	 * Translators: If there are characters in your language that are not supported
	 * by Montserrat, translate this to 'off'. Do not translate into your own language.
	 */
	if ( 'off' !== _x( 'on', 'Montserrat font: on or off', 'themeslug' ) ) {
		$fonts[] = 'Montserrat:400,700';
	}


	if ( $fonts ) {
		$fonts_url = add_query_arg( array(
			'family' => urlencode( implode( '|', $fonts ) ),
			'subset' => urlencode( $subsets ),
		), 'https://fonts.googleapis.com/css' );
	}


	return esc_url_raw( $fonts_url );
}
  
/**
 * Enqueue scripts and styles.
 */
function themeslug_scripts() {
	// Add custom fonts, used in the main stylesheet.
	wp_enqueue_style( 'themeslug-fonts', themeslug_fonts_url(), array(), null );

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

https://gist.github.com/philhoyt/04f5b60381956005a6cb38696decdc58

If you are in a similar position and trying to sharpen your WordPress skill set, I highly recommend breaking into some default themes. They are a plethora of knowledge.

Leave a Reply

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