How To Add Google Fonts To TinyMCE

Picture of Bullish Coder

Bullish Coder

I was working on a project a couple weeks ago and ran into a necessity for Google fonts for a cleaner design and modern look. The first question I had was, “is it possible to add google to TinyMCE?” The simple answer is yes. However, I spent hours browsing the web looking for a solution that was simple to implement while providing the capability desired. Below you will find my solution with some commentary.

TinyMCE Options Needed To Add Google Fonts

When we initialize our TinyMCE object we will focus on two options for the purpose of this tutorial.

  • content_css: This is used to load the google fonts via the google fonts API link. Look at the solution for the example that i’m using.
  • toolbar1: Used to populate the toolbar with fontselect which provides a UI to select fonts.
  • font_formats: This tells TinyMCE which fonts to show in the fontselect toolbar. Take a look at the solution for an example

One thing to note is that when using the option font_formats, it replaces the default items in the fontselect toolbar. The workaround that I am using, which is in the solution, is to add my google fonts as well as SOME system fonts that I use.

Some Things To Note

PLEASE don’t skip these since it will only serve to save you time.

  • The fonts are loaded for TinyMCE instances only. What this mean is that if you try to apply the google to any element outside of TinyMCE it will not work. I worked around this issue by adding the same google fonts to my projects main CSS.
  • using the font_formats option replaces the default options. I worked around this by adding any system fonts I needed.

The Solution

I saw many answers on the topic and while many roads led to the same results, I found the code below to be the simplest implementation.

tinymce.init({
            selector: '#<YOUR SELECTOR HERE>',
            plugins: 'print preview searchreplace autolink codesample code directionality visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help',
            toolbar1: 'formatselect | bold italic strikethrough forecolor backcolor | link | codesample code | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat | fontsizeselect | fontselect  ',
            image_advtab: true,
            content_css: ['https://fonts.googleapis.com/css?family=Lato|Montserrat|Open+Sans|Oswald|Raleway|Roboto&display=swap'],
            font_formats: 'Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;Montserrat=Montserrat,sans-serif;Roboto=Roboto, sans-serif;Oswald=Oswald, sans-serif;Raleway=Raleway, sans-serif'
        })

If there are any questions or comments just leave them below. 🙂

More to explorer 🧭

Leave a Reply