How to use Google Web Fonts in WordPress

comment 0
Labs

While working on a customer site I found out that the theme in use was not properly loading the Google Web Fonts.

After the usual research I was not able to find the solution anywhere om the web. Casually I found out that also the Twenty Twelve theme does not correctly load the Google Web Font that it is supposed to use.

If you look at the functions.php script in your twentytwelve folder you will find a nice explanation about how to use a Google Web Font, “Open Sans” in this case.

Unfortunately by looking at the source code of a Twenty Twelve theme you can see that the Google Web Font is not loaded as the code generated to load it is the following:

<link rel='stylesheet' id='twentytwelve-fonts-css' href='http://fonts.googleapis.com/css' type='text/css' media='all' />

The problem is that the URL of the font is missing the parameters needed to load the font. Try to click on the URL:

http://fonts.googleapis.com/css

And you will get a 400 error:

To properly load the Open Sans web font, the URL should look something like the following one:

http://fonts.googleapis.com/css?family=Open+Sans:400,600

If you click on the above link you will see the CSS code for the Open Sans font:

@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(http://themes.googleusercontent.com/static/fonts/opensans/v6/cJZKeOuBrn4kERxqtaUH3bO3LdcAZYWl9Si6vvxL-qU.woff) format('woff');
}
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
src: local('Open Sans Semibold'), local('OpenSans-Semibold'), url(http://themes.googleusercontent.com/static/fonts/opensans/v6/MTP_ySUJH_bn48VBG8sNSqRDOzjiPcYnFooOUGCOsRk.woff) format('woff');
}

Now, if your theme uses the Google Web Fonts the wrong way, you have two choices:

  1. Wait that the theme author fixes the problem – meanwhile your site does not look like you expect…
  2. Do it yourselves by searching for the code that loads the font in your theme – usually is in your main theme folder in the functions.php script; however be aware that if the theme gets an update and the font issue is not fixed you will need to edit the code again (so it’s a good idea to inform the theme author to fix the issue as soon as possible)

After playing around with different solutions, I found out that the following code works:

function load_google_web_font_sample() {
echo '<link href="'. ( is_ssl() ? 'https' : 'http' ) .'://fonts.googleapis.com/css?family=Open+Sans:400,600" rel="stylesheet" type="text/css">';
}
add_action( 'wp_head', 'load_google_web_font_sample', 0 );

If you need help to fix this issue on your site feel free to get in touch for a quote.

Leave a Reply