Are you looking to enhance the visual appeal of your WordPress theme by incorporating custom Google Fonts? The process is simpler than you might think. In this guide, we’ll walk you through registering and enqueue Google fonts to elevate the typography on your WordPress site.
Registering Custom Fonts
To begin, you need to register the custom fonts you wish to use. Below is a sample code snippet that demonstrates how to register fonts such as Oswald and Montserrat. Place this code in your theme’s functions.php
file:
/**
* Register custom fonts.
*/
function themeslug_fonts_url() {
$fonts_url = '';
$fonts = array();
$subsets = 'latin,latin-ext';
// Include Oswald font if not set to 'off'
if ( 'off' !== _x( 'on', 'Oswald font: on or off', 'themeslug' ) ) {
$fonts[] = 'Oswald:400,700';
}
// Include Montserrat font if not set to 'off'
if ( 'off' !== _x( 'on', 'Montserrat font: on or off', 'themeslug' ) ) {
$fonts[] = 'Montserrat:400,700';
}
// Generate fonts URL
if ( $fonts ) {
$fonts_url = add_query_arg(
array(
'family' => urlencode( implode( '|', $fonts ) ),
'subset' => urlencode( $subsets ),
),
'https://fonts.googleapis.com/css'
);
}
return esc_url_raw( $fonts_url );
}
Enqueuing Scripts and Styles
Next, you need to enqueue the scripts and styles that will load the custom fonts. Use the following code snippet:
/**
* Enqueue scripts and styles.
*/
function themeslug_scripts() {
// Add custom fonts to the main stylesheet
wp_enqueue_style( 'themeslug-fonts', themeslug_fonts_url(), array(), null );
}
// Hook into the wp_enqueue_scripts action
add_action( 'wp_enqueue_scripts', 'themeslug_scripts' );
Conclusion
By following these steps and incorporating the provided code snippets into your theme’s functions.php
file, you can effortlessly register and enqueue Google Fonts for your WordPress theme. This small customization can significantly improve the aesthetics and readability of your website. Experiment with different fonts to find the perfect combination that aligns with your site’s design and enhances the overall user experience.
Leave a Reply