How to add custom fonts in the editor

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:

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