Solution to render Shortcodes in Admin Editor

I have asked this question about a year ago and I am hoping there is some type of simple solution which will allow me achieve my objective. So here it goes:

I often utilize shortcodes within the Admin Editor but when I turn this over to client they often don’t understand how they work.

What I am looking for is a solution which would simply automatically render the associating output of shortcodes within the admin WYSIWYG editor.

From a visual perspective, I would like for this to display similar to when the “more” line show up or when an image is displayed within the editor. By this I mean that the user would see the output but would only be able to delete it but not edit the content of the rendered shortcode.

3

It’s actually not too bad to do what you’re asking. This should take you about an hour to do your first one, and 10 minutes to do subsequent ones.

Ultimately what you’re going to do is create a TinyMCE plugin. Here’s what you should arm yourself with to start:

  1. General guide to creating a tinymce plugin
  2. Example code from WordPress Core
  3. A general guide on adding a TinyMCE plugin to WordPress. I found this one, which seems adequate.

You now have all the tools to get ‘er done! Of all this, the code that will be of most interest to you is this block in the WP example code:

4   function replaceGalleryShortcodes( content ) {
5       return content.replace( /\[gallery([^\]]*)\]/g, function( match ) {
6           return html( 'wp-gallery', match );
7       });
8   }
9
10  function html( cls, data ) {
11      data = window.encodeURIComponent( data );
12      return '<img src="' + tinymce.Env.transparentSrc + '" class="wp-media mceItem ' + cls + '" ' +
13          'data-wp-media="' + data + '" data-mce-resize="false" data-mce-placeholder="1" alt="" />';
14  }

Here, the shortcode for a gallery gets replaced with an img tag. The img tag has the class wp-gallery, which gets styled by the CSS found here.

Edit 2016-04-06: Updated content and links for TinyMCE 4 and WordPress 4.4

Leave a Comment