4

I want to add styles to editor-style.css, based on the category the current post belongs to.

Therefore I would like to add the post classes - using get_post_class() - to the body of the TinyMCE iframe.

I've seen this question, but it's about adding classes via JavaScript, and I need it to be done via PHP so I can use get_post_class(). Neither can I use the admin_body_class filter, because that doesn't address the TinyMCE iframe.

How can I add the post's classes to the TinyMCE iframe?

2

The filter you're after is tiny_mce_before_init. Using this, we can hook into TinyMCE's 'init_array' and add body classes:

add_filter( 'tiny_mce_before_init', 'wpse_235194_tiny_mce_classes' );

function wpse_235194_tiny_mce_classes( $init_array ){

  global $post;

  if( is_a( $post, 'WP_Post' ) ){
    $init_array['body_class'] .= ' ' . join( ' ', get_post_class( '', $post->ID ) );
  }

  return $init_array;

}

We're joining the post classes with a space to convert them from an array to a string as required by TinyMCE, and we're also checking that we do actually have a valid post object, to avoid errors if you're using TinyMCE elsewhere (such as in widgets or the like).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.