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

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