aitor
July 29, 2022, 6:25am
1
Styles from editor.scss are enqueued, but the font path is wrong resolved:
GET http://angelgiraldez.test/fonts/BarlowCondensed-Italic.woff net::ERR_ABORTED 404 (Not Found)
How do you get working custom fonts in the editor?
// editor.scss
@font-face {
font-family: 'Barlow Condensed';
src: url('~@fonts/Barlow_Condensed/BarlowCondensed-Italic.woff2') format('woff2'),
url('~@fonts/Barlow_Condensed/BarlowCondensed-Italic.woff') format('woff');
font-weight: normal;
font-style: italic;
font-display: swap;
}
.wp-block {
font-family: 'Barlow Condensed', sans-serif;
}
You either have to ensure the path is stylesheet-relative for editor-stylesheets, or you enqueue these frontend styles as editor styles - by its path instead of URI - to let the Gutenberg editor post-process the styles and rewrite the URLs used therein:
With latest roots/acorn release version 2.1.1 the assets now have a relativePath() function , which simplifies this code a lot:
namespace App;
use function Roots\asset;
add_action('after_setup_theme', function () {
// Add frontend styles as editor styles
// Must be added by relative path (not remote URI)
// (@see https://core.trac.wordpress.org/ticket/55728#ticket)
$relCssPath = asset('app.css')->relativePath(get_theme_file_path());
add_editor_style($relCssPath);
});
2 Likes
Alternatively, you could use the theme.json
API.
There is a helper in @roots/sage
extension for working with it.
app.wpjson.settings((theme) =>
theme.set("typography.fontFamilies", [
{
fontFamily: `"public-sans", sans-serif`,
name: "Public Sans",
slug: "public-sans",
fontFace: [{
fontFamily: "Public Sans",
src: ["file:./resources/fonts/public-sans.ttf"],
}],
},
])
);
The json, if you prefer:
{
"$schema": "https://schemas.wp.org/trunk/theme.json",
"version": 2,
"settings": {
"typography": {
"fontFamilies": [
{
"fontFamily": "\"public-sans\", sans-serif",
"name": "Public Sans",
"slug": "public-sans",
"fontFace": [
{
"fontFamily": "Public Sans",
"src": ["file:./resources/fonts/public-sans.ttf"]
}
]
}
]
}
}
}
I think it’s dreadful to work with but ymmv.
5 Likes