If there are only a few Google fonts loaded by a theme/plugin and you want to remove them by yourself without a plugin, here are ways to do that with a few lines of PHP code.
There are two ways:
- Find out the code that registers Google fonts with a handle name, then remove those handles one by one. This applies when you know which fonts to remove and reserve the rest.
-
Remove all the handles of fonts each of which is registered with an URL containing
'fonts.googleapis.com'
at one time. This applies when you know which fonts to reserve and remove the rest.
You can put the code inside the functions.php
of a child theme or create a new plugin to do that (See more at Ways to custom WordPress, it is pretty simple).
Way 1. Remove a font with a known handle
Assume you want to remove the Google fonts added by a theme in which the code adding fonts may like this:
function thetheme_enqueue_scripts () {
wp_enqueue_style('thetheme-fonts',
'https://fonts.googleapis.com/css?family=Libre+Franklin');
}
add_action('wp_enqueue_scripts', 'thetheme_enqueue_scripts');
The function thetheme_enqueue_scripts()
registers Google fonts with a stylesheet handle named as thetheme-fonts
(the first parameter passed to wp_enqueue_style()
). Then it is added to action wp_enqueue_scripts
with a default priority (10).
Stylesheet handle
The handle is used to identify a stylesheet to be added to a page. In the final HTML file, it is attached with
-css
and used as theid
of a “ tag.
Then you can remove it with below code:
function mycustom_remove_google_fonts() {
wp_dequeue_style('mytheme-fonts');
}
add_action('wp_enqueue_scripts', 'mycustom_remove_google_fonts',
PHP_INT_MAX);
Here mycustom_remove_google_fonts()
passes the handle thetheme-fonts
to wp_dequeue_style()
to remove the associated stylesheet.
Note we can only remove a stylesheet which has been registered. Therefore we add our action with a higher value of priority to make sure it is called at a later point.
Way 2. Remove all fonts from fonts.googleapis.com
Below code removes all fonts from fonts.googleapis.com but the font registered with the handle myplugin-fonts
.
function mycustom_remove_google_fonts () {
// The fonts to be reserved.
$reserved_font_handles = [
'myplugin-fonts' => true,
];
// Remove all styles whose src contains 'fonts.googleapis.com' except those reserved.
$wp_styles = wp_styles();
foreach ($wp_styles->registered as $style) {
if (strpos($style->src, 'fonts.googleapis.com') !== false ) {
$handle = $style->handle;
if (!array_key_exists($handle, $reserved_font_handles)) {
wp_dequeue_style($handle);
}
}
}
}
add_action('wp_enqueue_scripts', 'mycustom_remove_google_fonts',
PHP_INT_MAX);
Note if you are using Google Ads plan, it may adds Google fonts and you should take care of that and better only remove the known Google fonts loaded by plugins/themes.
Resource
wp_enqueue_scripts
-
Use a plugin to remove Google fonts if you do not want to bother: