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:
-
OMGF (Host Google Fonts Locally) - Automatically downloads and hosts Google Fonts locally
-
Google Fonts Typography - Adds 1000+ Google Fonts with live customizer preview
Best Practices
- Always use
wp_enqueue_scripts
hook to add fonts
- Consider using font-display: swap for better performance
- Limit the number of font weights to improve load times
- 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.