tools/google-fonts-loader-generator
Google Fonts Loader Generator
Enqueue Google Fonts properly: a css2 URL with the weights and italics you picked, the null version argument that keeps WordPress from appending ?ver to it, and a preconnect to the host the font files actually come from.
snippet.php
<?php
/**
* Google Fonts
*
* Inter.
*
* Generated by wp-skills.com
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Loads the font stylesheet.
*
* The fourth argument is null, and it has to be spelled out. wp_enqueue_style()
* defaults $ver to false, which means "use the WordPress version" — so leaving
* it off appends ?ver=7.1 to Google's URL and changes it on every WordPress
* update. Only null suppresses the query argument entirely. Measured: omitted
* gives &ver=7.1, '1.0' gives &ver=1.0, null gives the URL untouched.
*
* The ampersands come out as & in the rendered <link>. That is correct
* HTML escaping, not a broken URL — browsers read it as &.
*/
function wp_skills_google_fonts() {
wp_enqueue_style(
'wp-skills-google-fonts',
'https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap',
array(),
null
);
}
add_action( 'wp_enqueue_scripts', 'wp_skills_google_fonts' );
add_action( 'enqueue_block_assets', 'wp_skills_google_fonts' );
/**
* Opens the connection to Google's font host before the browser needs it.
*
* Only fonts.gstatic.com, and only preconnect. WordPress already emits a
* dns-prefetch for fonts.googleapis.com by itself — wp_dependencies_unique_hosts()
* collects the host of every enqueued stylesheet, and the stylesheet above is
* one — so adding that would be a duplicate. Nothing is enqueued from
* fonts.gstatic.com, which is where the font *files* come from, so it gets
* neither hint unless it is asked for here.
*
* crossorigin is required rather than decorative: font files are fetched in
* CORS mode, and a preconnect without it opens a connection the font request
* cannot reuse.
*/
function wp_skills_google_fonts_preconnect( $urls, $relation_type ) {
if ( 'preconnect' === $relation_type ) {
$urls[] = array(
'href' => 'https://fonts.gstatic.com',
'crossorigin' => 'anonymous',
);
}
return $urls;
}
add_filter( 'wp_resource_hints', 'wp_skills_google_fonts_preconnect', 10, 2 );