X

How to add WP’s customizer CSS into the classic editor

Recently, a newly acquired client needed the styling from the Customizer’s custom CSS to show in the classic editor (TinyMCE). In all my years of working with WordPress, this was the first time I’d had this request, so, knowing that you can inject styling into the TinyMCE editor, I set about finding a solution.

There are several ways to add custom styling to the classic editor, including:

  • loading a custom stylesheet, using add_editor_style('custom-editor-style.css'),
  • loading a custom stylesheet, using add_filter('mce_css'), and
  • loading dynamic styles, using add_filter('tiny_mce_before_init') and appending style properties to $settings['content_style'].

In this post, we’ll focus on the latter, which we can use to get the Customizer’s CSS.

Loading Customizer CSS into the Classic Editor

The Customizer’s theme CSS is stored in the post table, with post type custom_css. To get this we’ll use get_posts(), then we’ll append the post_content to $mce_settings['content_style'] (after sanitising it). Here’s the WordPress filter, note that I’ve used an anonymous function, but you don’t have to:

add_filter('tiny_mce_before_init', function ($mce_init) {
    $customizer_posts = get_posts('post_type=custom_css&numberposts=1');
    $styles = $customizer_posts[0]->post_content ?? '';
    
    // return early if no stlying was found
    if (!$styles) return $mce_init;
    
    // sanitise ready for use
    $styles = sanitize_text_field($styles);
    
    // add styling
    if (isset($mce_init['content_style'])) {
        $mce_init['content_style'] .= " $styles ";
    } else {
        $mce_init['content_style'] = " $styles ";
    }
    
    // return updated settings
    return $mce_init;
});

And that’s how to add customizer CSS into the classic editor.

If you’re struggling with this or any other WordPress challenge, don’t hesitate to get in touch for further support.

Related Post

This website uses cookies.