Steve Grunwell

Open-source contributor, speaker, and electronics tinkerer

The WordPress TinyMCE editor, modified so the block formats read "put whatever you want in here"

Customizing the WordPress TinyMCE Block Formats

This morning, I was scrolling through Twitter as I tried to wake up (as I do most every morning), when I came across this tweet from the wonderful Carrie Dils asking how to customize the WordPress TinyMCE block formats:

“That’s funny,” I thought to myself, “I used to do those customizations on client sites all the time. In fact, some of those customizations are even in my (now-abandoned) WordPress Starter Theme repo on GitHub!

I was able to throw together a quick gist to demonstrate how to pull off a <code> block format, but doing so reminded me how much of a struggle it was to figure that all out to begin with. In the interest of helping everyone else configure TinyMCE, here’s a quick breakdown:

First, we’re hooking into the “tiny_mce_before_init” filter, which lets us access the configuration for TinyMCE. To give you a sense of what this looks like, here are some of the WordPress defaults:

This is a PHP array representation of the settings that will be passed to TinyMCE when it’s initialized. Settings that are missing will naturally fall back to their TinyMCE-provided defaults. We can take advantage of this fact to adjust TinyMCE’s configuration in all sorts of ways, including editing the block_formats setting.

Note that TinyMCE is expecting a semi-colon-delimited string, so the code snippet above writes out each format as a value in the $block_formats array, then uses implode( ';', $block_formats) to bring them all together. You’ll also need to be respectful of other plugins that might be editing the block_formats configuration (the example above will wholesale rewrite $init['block_formats'], whether it exists or not).

For more on customizing TinyMCE within WordPress, be sure to check out the “TinyMCE Custom Styles” article in the WordPress Codex!

Previous

Two new micro-libraries for WordPress

Next

A Crash-course in PHP Namespaces for WordPress Developers

1 Comment

  1. Reformat

    Really handy this, just wish I could figure out how to easily add classes at this level. When I use style_formats it adds the horrible Formats dropdown which adds classes on rather than toggle them. I guess core has abandoned this now in favour of block editor though.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Be excellent to each other.