How to wrap the content of the main tinyMCE editor with extra tags

I’m on WP 4.6, which has tinyMCE 4. I need to make the contents of my post editor visual tab more WYSIWYG. I’m attaching a CSS file containing my front end styles to the editor using add_editor_style. But for the contents of the editor to take on many of those styles I also need to wrap them in a couple of HTML tags – divs with particular classes.

The tinyMCE documentation is a bit better than it used to be, but it’s still a nightmare trying to figure out how to grab the content and wrap it when tinyMCE inits. I’m trying this test to append a string to the content:

tinymce.init({
    selector: 'textarea#content.wp-editor-area',
    setup   : function(ed) {
        ed.on('BeforeSetContent', function(event) {
            event.content += '????????????????????????????????????????';
        });
    }
});

But this doesn’t seem to be selecting the tinyMCE instance of the main post editor. I can’t find any documentation on what is supported for the selector, and even whether it is necessary. Can anyone point me in the right direction?

1 Answer
1

Personally, I style all of the content placed within the WP Editor using just a single class, typically .entry-content which I’ve used in the example below.

When outputting the content from the WP Editor on the front end, I wrap it in div.entry-content. Using a single HTML class simplifies things:

style.css

.entry-content h2 {
    color: purple;
}
/* etc ... */

I’m also using add_editor_style() to load my theme’s default stylesheet into tinyMCE:

function wpse247805_editor_styles() {
    // Use our existing main stylesheet for TinyMCE too.
    add_editor_style( 'style.css' );
}
add_action( 'after_setup_theme', 'wpse247805_editor_styles' );

I use the wpse247805_editor_styles_class() function below, which simply adds the .entry-content class to the tinyMCE <body> element.

/**
 * Add .entry-content to the body class of TinyMCE.
 * @param array $settings TinyMCE settings.
 * @return array TinyMCE settings.
 */
function wpse247805_editor_styles_class( $settings ) {
    $settings['body_class'] = 'entry-content';
    return $settings;
}
add_filter( 'tiny_mce_before_init', 'wpse247805_editor_styles_class' );

Sometimes I find it necessary to override the styles applied to .entry-content inside of the WP Editor. I use Sass and I have a partial dedicated for this purpose.

// TinyMCE .wp-content overrides.
body#tinymce.wp-editor {

    // Override Foundation's height: 100%; because WP Editor in 4.0+ won't scroll down all of the way otherwise.
    height: auto !important;

    &.entry-content {
        margin: 16px;
    }
}

Leave a Comment