The right way to add Google Fonts to WordPress

Another quick service post from my archive of things that I need to add to my company blog but haven't done yet.

Today's topic: how to properly enqueue Google Fonts to your WordPress without a plugin.

I'll just pull the code straight out of my theme so that you can see how it would work. We're going to use the URL directly from Google here:

http://fonts.googleapis.com/css?family=Oswald:400,300,700

In your functions.php:

/**
 * Additional Styles
 * @since 1.0.0
 */

function child_styles() {
    if ( !is_admin() ) {

        // register styles
        wp_register_style('googlefont-oswald', 'http://fonts.googleapis.com/css?family=Oswald:400,300,700', array(), false, 'all');

        // enqueue styles
        wp_enqueue_style('googlefont-oswald');
    }
}

add_action('wp_enqueue_scripts', 'child_styles');

Repeat the inner part for additional fonts. In other words, register and enqueue each set inside the brackets. The function is called "child_styles()" because I would register all of my .css files inside of one function. You can call yours whatever you like.

I'm pretty sure a number of you will find that useful.

Cheers,
Ian

  • Imperative Ideas
    • HummingBird

    Sure thing.

    There are so many little tricks to WordPress that make it run more smoothly. Even the WordPress .htaccess section is inefficient on its own. Granted, this would have to be re-written for multi-site but if you replace

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>

    with

    RewriteEngine on
    # Unless you have set a different RewriteBase preceding this point,
    # you may delete or comment-out the following RewriteBase directive:
    RewriteBase /
    # if this request is for "/" or has already been rewritten to WP
    RewriteCond $1 ^(index.php)?$ [OR]
    # or if request is for image, css, or js file
    RewriteCond $1 .(gif|jpg|jpeg|png|css|js|ico)$ [NC,OR]
    # or if URL resolves to existing file
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    # or if URL resolves to existing directory
    RewriteCond %{REQUEST_FILENAME} -d
    # then skip the rewrite to WP
    RewriteRule ^(.*)$ - [S=1]
    # else rewrite the request to WP
    RewriteRule . /index.php [L]

    [source]

    You will see a speed boost in page response time in the logs.

    The platform is full of this stuff. I wish I could efficiently share all of it.

  • PC
    • WPMU DEV Initiate

    That is indeed great to read. The world is full of knowledge, and the best place to share it is the forums like ours.

    We are working hard on a community area so in future we might have a place where things like this can be shared and spread :slight_smile:

    Cheers. PC

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.