-
-
Save kevinwhoffman/5e5b83f7aef6eae92a9ddd939b7a94ca to your computer and use it in GitHub Desktop.
<?php | |
/** | |
* Adds styles from customizer to head of TinyMCE iframe. | |
* These styles are added before all other TinyMCE stylesheets. | |
* h/t Otto. | |
*/ | |
function kwh_add_editor_style( $mceInit ) { | |
// This example works with Twenty Sixteen. | |
$background_color = get_theme_mod( 'background_color' ); | |
$styles = '.mce-content-body { background-color: #' . $background_color . '; }'; | |
if ( !isset( $mceInit['content_style'] ) ) { | |
$mceInit['content_style'] = $styles . ' '; | |
} else { | |
$mceInit['content_style'] .= ' ' . $styles . ' '; | |
} | |
return $mceInit; | |
} | |
add_filter( 'tiny_mce_before_init', 'kwh_add_editor_style' ); |
@Otto42 Done.
@kevinwhoffman In testing this:
$mceInit['content_style'] .= $styles . ' ';
Returned a PHP Notice:
Notice: Undefined index: content_style
Removing the period before the equals avoids that for me.
Other than that this works perfectly. I love that it's just extending the default TinyMCE inline styles. Really smooth solution. Thanks!
@mathetos Thanks, updated to remove period.
Removing the period defeats the stated purpose of wrapping with the spaces: allowing other plugins to add more styles.
It should probably be something like this (and then you can remove the first line to set the empty space.)
if (!isset($mceInit['content_style'])) {$mceInit['content_style'] = $styles . ' ';}
else {$mceInit['content_style'] .= ' ' . $styles . ' ';}
Thanks @majick777. You are right if we remove the period then any existing styles that are using the same hook would be wiped out. I edited the gist to add your conditional. Works great.
Just another note, double quotes will break the tinyMCE javascript (like new lines) because tinyMCE adds the CSS via javascript and wraps the call in double quotes. So they need to be replaced with single quotes or double escaped and then they work fine. :-)
Note that you'll probably want to add some leading and trailing spaces to the css, in case anything else is hooking in there as well.