Skip to content

Instantly share code, notes, and snippets.

@kevinwhoffman
Last active January 30, 2022 14:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinwhoffman/5e5b83f7aef6eae92a9ddd939b7a94ca to your computer and use it in GitHub Desktop.
Save kevinwhoffman/5e5b83f7aef6eae92a9ddd939b7a94ca to your computer and use it in GitHub Desktop.
Add customizer styles to visual editor
<?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
Copy link

Otto42 commented Jul 15, 2016

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.

@kevinwhoffman
Copy link
Author

@Otto42 Done.

@mathetos
Copy link

@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.

@mathetos
Copy link

Other than that this works perfectly. I love that it's just extending the default TinyMCE inline styles. Really smooth solution. Thanks!

@kevinwhoffman
Copy link
Author

@mathetos Thanks, updated to remove period.

@majick777
Copy link

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 . ' ';}

@kevinwhoffman
Copy link
Author

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.

@majick777
Copy link

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. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment