I’ve always really liked how Sage loads your theme’s stylesheet into the admin editor so that you can see your styles reflected as you edit your content, and I’ve found a couple of ways over time to extend that a little bit. Today, that was getting the font I’m using on my current project (from Google Fonts) to apply there.
When you use @font-face to load font files in your CSS, those fonts should be available in the admin editor with no extra steps–but if you’re using Google Fonts, that’s not the case. An extra couple of steps are required.
Note: This post originally used a method based on Tom McFarlin’s post here, adapted to Sage’s configuration. @alwaysblank came up with a much simpler method, and that’s what’s included here now. All credit to him!
Here’s what the front end looks like (what we’re trying to approximate in the editor):
The serif font used for the body is Merriweather.
Abstract your Google Fonts stylesheet URL
The Google Fonts stylesheet URL will be used in both your theme’s front end and WordPress admin, so let’s define it once for both. In setup.php
:
function google_fonts_url()
{
return 'https://fonts.googleapis.com/css?family=' . urlencode('Merriweather:300,300i,900,900i');
}
Replace the part inside urlencode
with the appropriate families from your own Google Fonts URL. It’s encoded because otherwise WordPress would break the URL up where each comma is when we include it in the editor.
Note: if the font name has a plus in it, replace that with a space before encoding, like so (‘Open Sans’ instead of ‘Open+Sans’):
function google_fonts_url()
{
return 'https://fonts.googleapis.com/css?family=' . urlencode('Open Sans:400,400i,600,800');
}
Your wp_enqueue_style
line for adding the fonts to your theme’s front end should now look like this (also in setup.php
):
wp_enqueue_style('google/fonts', \App\google_fonts_url(), false, null);
If you were using a different method to add the fonts to your theme, adapt these instructions as needed.
Add the Google Fonts stylesheet to the editor
To add the fonts to the TinyMCE editor, add the stylesheet URL to the list of URLs loaded in the editor by WordPress, using the mce_css
filter. In setup.php
:
add_filter('mce_css', function ($sheets) {
return "$sheets," . \App\google_fonts_url();
});
Reload your editor page and enjoy
That should be all you have to do (but you may need to do a hard refresh)! Here’s how it looks for me: