Site icon Hip-Hop Website Design and Development

Loading a self-hosted custom @font-face into TinyMCE dropdowns (Classic Editor) via ‘tiny_mce_before_init’ filter

I can’t work out how to load self-hosted custom fonts for preview in the font_formats and ‘style_formats` dropdown in TinyMCE (Classic Editor).

TinyMCE documentation shows this example for loading a Google Fonts stylesheet
(https://www.tiny.cloud/blog/tinymce-custom-font-family/):

tinymce.init({
  /* ... */
  content_style:
    "@import url('https://fonts.googleapis.com/css2?family=Oswald&display=swap'); body { font-family: Oswald; }",
});

…but when I try to apply this method to load @font-face instead, the dropdown previews still use fallback fonts. I can tell that TinyMCE is at least loading them somewhere, because if I use an incorrect path, I get a 404 error.

Example functions.php code:

function my_tinyMCE_init($init){
  // Works: customizes which fonts display in font_formats dropdown
  $init['font_formats'] = 'Arial=arial,helvetica,sans-serif;Georgia=georgia,serif;DIN=din,helvetica,sans-serif;Freight Macro=freight,serif;Lydia=lydia,sans-serif;Druk=druk,arial black,sans-serif;';
  
  // Works: customizes style_formats menu)
  $style_formats = [  
    // (arrays of basic and custom style formats here)
  ];
  $init['style_formats'] = json_encode( $style_formats );  

  // DOESN'T WORK: load font files into TinyMCE so they preview correctly in above menus
  $init['content_style'] = "@font-face{font-family:'freight';font-style:normal;font-weight:400;src:url('".get_template_directory_uri()."/fonts/freight/FreightMacroProBookRegular/font.woff2') format('woff2'),url('".get_template_directory_uri()."/fonts/freight/FreightMacroProBookRegular/font.woff') format('woff')}";

  return $init;
}
add_filter('tiny_mce_before_init', 'my_tinyMCE_init');

For extra clarification: I am not seeking to load the custom fonts for preview in the WYSIWYG editor iframe itself — that already works through the loaded editor-styles.css stylesheet. It’s only the Style Formats and Font Formats dropdowns in the toolbar that don’t load the fonts. Though, on that note, I also did try to just @import that stylesheet again through ['content_style'] to see if it would work for the dropdowns (as it contains all of the @font-face declarations), but that also does not work.