Google Fonts are a great alternative to expensive font foundries like Adobe Typekit or free ones like Font Squirrel and Edge Web Fonts. Why great? In my opinion it’s mostly the amount of fonts available and their ease of use. In pure HTML pages, you just paste a bit of code that you got by choosing your font, and you’re all set. Simplicity is the key here.
Notice: This article was written in 2016. WordPress has changed a lot since then, so take this article with a grain of salt…
So naturally we can ask ourselves: how to use them in our WordPress themes?
When I first started working on WordPress themes the way I included them was just to enqueue the code I got from Google in my wp_enqueue_scripts hook like
wp_enqueue_style('yourtheme-google-fonts', '//fonts.googleapis.com/css?family=Open+Sans', array(), null);
Code language: PHP (php)
But since then I think I’ve grown and learned the right way to do it. I’ll explain to you how to include the Google Fonts in your theme Customizer and set it all up.
Google Fonts API key and customizer
First thing you’ll need to get is a Google Fonts API key. To do that go to Google developers console and follow the instructions to get your API key. It’s super simple, you shouldn’t have any issues with that.
We need this key so that we can create a custom control in our Theme customizer. You can learn all about it in my previous posts here and here. In our customizer.php we’ll add a separate Fonts section, and in it we’ll add one setting and control.
/**
------------------------------------------------------------
SECTION: Fonts
------------------------------------------------------------
**/
$wp_customize->add_section('section_fonts', array(
'title' => esc_html__('Fonts', 'mytheme'),
'priority' => 0,
));
/**
Main Google Font Setting
**/
$wp_customize->add_setting( 'main_google_font_list', array(
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control( new Google_Font_Dropdown_Custom_Control( $wp_customize, 'main_google_font_list', array(
'label' => 'Main Google Font',
'section' => 'section_fonts',
'settings' => 'main_google_font_list',
)));
Code language: PHP (php)
As you can see I added one setting and one control for main fonts. You could extend this to include header fonts, post fonts, footer fonts etc. Just have in mind that the more fonts you have, the more fonts you’ll load and this could impact your page performance (speed).
Next you’ll need the custom control called Google_Font_Dropdown_Custom_Control. In your custom_controls.php you’ll add
class Google_Font_Dropdown_Custom_Control extends WP_Customize_Control{
private $fonts = false;
public function __construct($manager, $id, $args = array(), $options = array()){
$this->fonts = $this->get_google_fonts();
parent::__construct( $manager, $id, $args );
}
public function render_content(){
?>
<label class="customize_dropdown_input">
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<select id="<?php echo esc_attr($this->id); ?>" name="<?php echo esc_attr($this->id); ?>" data-customize-setting-link="<?php echo esc_attr($this->id); ?>">
<?php
foreach ( $this->fonts as $k => $v ){
echo '<option value="'.$v['family'].'" ' . selected( $this->value(), $v['family'], false ) . '>'.$v['family'].'</option>';
}
?>
</select>
</label>
<?php
}
public function get_google_fonts(){
if (get_transient('mytheme_google_font_list')) {
$content = get_transient('mytheme_google_font_list');
} else {
$googleApi = 'https://www.googleapis.com/webfonts/v1/webfonts?sort=alpha&key=AIzaSyD9cCtZWra_aNI4y4krjYpT4Id2PaP_Skg';
$fontContent = wp_remote_get( $googleApi, array('sslverify' => false) );
$content = json_decode($fontContent['body'], true);
set_transient( 'mytheme_google_font_list', $content, 0 );
}
return $content['items'];
}
}
Code language: JavaScript (javascript)
First you create a constructor that will get all the fonts from Google Fonts API. In the get_google_fonts() function you’ll store the fonts in a transient. Transients are a great way to store the data in the database for certain amount of time. In our case it’s 0 so it never expires, because we assume that fonts don’t get added to the google font list that often. But here you could set the expiration of transient to several months if you wish. Now if transient exists you’ll pull the data from it, but if it doesn’t (which it won’t on your first run) you need to create it.
The $googleApi variable contains the link to the google fonts with your key you created earlier – here it’s AIzaSyD9cCtZWra_aNI4y4krjYpT4Id2PaP_Skg, in your case it will be something different of course. Just paste your key here and it should work. Next you are fetching the content using wp_remote_get() function, and you are decoding the JSON response you got from it.
In the render_content() function we just created a simple HTML select with the list of our Google Fonts.
Great, we have our fonts in the customizer, now we need to enqueue them in our theme.
Enqueuing the fonts
To make our fonts available in our theme we need to enqueue them properly. Inside the wp_enqueue_scripts hook add
wp_enqueue_style('yourtheme-google-fonts', yourtheme_fonts_url(), array(), null);
Next thing you need is the aforementioned function so below in your functions.php just add
/********* Google Fonts URL function ***********/
if ( ! function_exists( 'yourtheme_fonts_url' ) ){
function yourtheme_fonts_url() {
$fonts_url = '';
$content_font = get_theme_mod('main_google_font_list', '');
// Translators: If there are characters in your language that are not supported by Google font, translate it to 'off'. Do not translate into your own language.
// $content_font = _x( 'on', ''.$content_font.' font: on or off', 'yourtheme' );
if ( 'off' !== $content_font ) {
$font_families = array();
if ( 'off' !== $content_font ) {
$font_families[] = $content_font;
}
$query_args = array(
'family' => urlencode( implode( '|', array_unique($font_families) ) ),
);
$fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' );
}
return esc_url_raw( $fonts_url );
}
}
Code language: PHP (php)
If you created more settings, just add them in a variable like $content_font , and add them in the if condition like this for instance
/********* Google Fonts URL function ***********/
if ( ! function_exists( 'yourtheme_fonts_url' ) ){
function yourtheme_fonts_url() {
$fonts_url = '';
$content_font = get_theme_mod('main_google_font_list', '');
$header_font = get_theme_mod('header_google_font_list', '');
// Translators: If there are characters in your language that are not supported by Google font, translate it to 'off'. Do not translate into your own language.
// $content_font = _x( 'on', ''.$content_font.' font: on or off', 'yourtheme' );
// $header_font = _x( 'on', ''.$header_font.' font: on or off', 'yourtheme' );
if ( 'off' !== $content_font || 'off' !== $header_font ) {
$font_families = array();
if ( 'off' !== $content_font ) {
$font_families[] = $content_font;
}
if ( 'off' !== $header_font ) {
$font_families[] = $header_font;
}
$query_args = array(
'family' => urlencode( implode( '|', array_unique($font_families) ) ),
);
$fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' );
}
return esc_url_raw( $fonts_url );
}
}
Code language: PHP (php)
And that’s it. You’ll have all the fonts loaded in your theme, and you can use it in your CSS as you wish.
Hope this code will be helpful, if you have any questions or comments just use the comment section below. Happy coding!
Leave a Reply