Integrate Google Fonts in Your WordPress Theme

Marc S. Dec 23, 2024 Styling
How can I use different fonts from Google on my website?
What is the proper way to enqueue Google Fonts in a WordPress theme using wp_enqueue_style?
Andy answered Dec 23, 2024

Integrating Google Fonts Using functions.php

The most efficient way to add Google Fonts to your WordPress theme is through the wp_enqueue_style function. Here's how to implement it:

Add this code to your theme's functions.php file:

Basic implementation for a single font:

function add_google_fonts() {
    wp_enqueue_style('google-fonts', 'https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap', array(), null);
}
add_action('wp_enqueue_scripts', 'add_google_fonts');

For multiple fonts with different weights:

function add_multiple_google_fonts() {
    wp_enqueue_style('google-fonts', 'https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&family=Roboto:wght@300;400;700&display=swap', array(), null);
}
add_action('wp_enqueue_scripts', 'add_multiple_google_fonts');

To use the fonts in your CSS:

body {
    font-family: 'Open Sans', sans-serif;
}

h1, h2, h3 {
    font-family: 'Roboto', sans-serif;
}

For better performance, you can also host Google Fonts locally. Here's how to implement it with local hosting:

function add_local_google_fonts() {
    wp_enqueue_style('local-google-fonts', get_template_directory_uri() . '/assets/fonts/fonts.css', array(), '1.0.0');
}
add_action('wp_enqueue_scripts', 'add_local_google_fonts');

Alternative Plugin Solutions

If you prefer a plugin solution, these are reliable options:

  1. OMGF (Host Google Fonts Locally) - Automatically downloads and hosts Google Fonts locally
  2. Google Fonts Typography - Adds 1000+ Google Fonts with live customizer preview

Best Practices

  1. Always use wp_enqueue_scripts hook to add fonts
  2. Consider using font-display: swap for better performance
  3. Limit the number of font weights to improve load times
  4. Consider hosting fonts locally for GDPR compliance and better performance

Performance Tip

For optimal loading, use the preconnect hint by adding this code to your theme's functions.php:

function preconnect_google_fonts() {
    echo '<link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>';
}
add_action('wp_head', 'preconnect_google_fonts', 7);

Remember to replace the font families in the examples with your chosen Google Fonts.