How to add custom CSS (theme option) to TinyMCE?

I’m trying to add custom CSS (set via theme options) to the TinyMCE visual editor in WordPress. On the front end, the theme generates this CSS and outputs it on the wp_head hook. The problem I’m running into is being able to add that CSS output to the editor.

This can’t be done with add_editor_style( 'editor-style.css' ) because we need to use PHP to access the theme option.

As an example of how it works on the front end:

add_action( 'wp_head', 'my_custom_colors' );

function my_custom_colors() {
    $color_1 = get_theme_mod( 'color_1', 'cc4a00' );

    echo "<style type="text/css">a { color: #{$color_1}; }";
}

I need a method for getting that custom style into the visual editor. Any help would be greatly appreciated.

5

Solution 1

This works as javascript solution:

Example:

tinyMCE.activeEditor.dom.addStyle('p {color:red; font-size:28px;}');

just open your js console and paste it for a quick test.
To target a specific editor one should use:

tinyMCE.getInstanceById('##editorID##').dom.addStyle('p {color:red; font-size:28px;}');

This will inject the provided string into the editors iframe <head><style id="mceDefaultStyles"></style> ...

Solution 2

Use wp_ajax as callback handler to add dynamic styles on editor init by using a filter

add_filter('tiny_mce_before_init', 'dynamic_editor_styles', 10);

function dynamic_editor_styles($settings){
    // you could use a custom php file as well, I'm using wp_ajax as
    // callback handler for demonstration
    // content_css is a string with several files seperated by a comma
    // e.g. file1, file2, ... extend the string

    $settings['content_css'] .= ",".admin_url('admin-ajax.php') ."/?action=dynamic_styles";
    
    return $settings;
}

// add wp_ajax callback
add_action('wp_ajax_dynamic_styles', 'dynamic_styles_callback');
function dynamic_styles_callback(){
    echo "p {color:red} h1{font-size:48px;}";
}

Leave a Comment