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.
Solution 1
This works as javascript solution:
Example:
just open your js console and paste it for a quick test.
To target a specific editor one should use:
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
WordPress provides a
mce_css
filter, that can be used to add custom stylesheets to the Visual Editor. According to the Codex:Example Codex filter callback, modified for a Theme:
I accepted the solution above by @ungestaltbar. However, I wanted to expand on this answer a bit with the full solution that I am using so that others could see how it works.
I’m hoping it’s okay to post another answer here like this. I didn’t see a way to post this in direct reply to my accepted solution. I’m still learning how to use WPSE.
I am probably late to this party but after using the above solution, I soon realized that page load speed of the editor had severely been crippled!
Taking a keen look at the code, I realized that the code keeps executing long after tinyMCE.activeEditor has been initialized.
The code uses The setInterval() method which evaluates an expression at specified intervals, I believe that was because you couldn’t determine at what point during code execution “activeEditor” will be available. This is what brought the page speed down to its knees.
A much better solution I am using to build a plugin is this
Here a native TinyMCE listener is used to execute the code after the active editor is initialized. I hope this will help someone out there.
Kind regards.
This is a modified solution posted on the WordPress.org forums for this question: http://wordpress.org/support/topic/customdynamic-css-in-tinymce?replies=14#post-4827573
This definitely works. I’m no JS guru though, so I’m not entirely sure if this is the best solution.
This could also be added to a JS file. You could easily pass variables via
wp_localize_script()
with that.