How to Use Multiple WYSIWYG (TinyMCE) Visual Editors in Your WordPress Metaboxes

Ever since WordPress invented the metabox, people have been trying to put the rich text editor (in WP this is provided by TinyMCE) into their metaboxes.  And it makes sense.  Sure us uber-geeks know the HTML tags required to make some text bold, but most of the world does not., but they do know how to click on the “B” button.  So if we’re building a theme that requires multiple blocks of content it’s nice to reuse the visual editor.

I’ve been using the WP Alchemy Class by Dimas Begunoff to build my metaboxes for a while now.  It gives a lot of power to build really complicated field sets, especially repeating ones.  For a long time using the visual editor in the metaboxes was elusive.  Dimas wrote an article on How to Use Multiple WordPress WYSIWYG Visual Editors and it worked, up to a point.  Because TinyMCE is fickle (and despite their tagline being “Easy to Integrate”) this code didn’t work for repeating groups, which in my mind is the strength of Alchemy.

As of WordPress 3.3 you can finally use the built-in wp_editor() function for multiple editors in your metaboxes, but again these must be defined in advance.  You can’t use this function with WPA’s dynamically generated fields.

So, repeatable, sortable WYSIWYG (TinyMCE) rich-text editors has been the elusive, ultimate dream of WP Alchemists.  The <cough>”Holy Grail”</cough> of WP Alchemy.  But after a lot of head-banging effort, I think I have it!

I have create a Twenty Eleven child theme that shows WP Alchemy-powered metaboxes with repeatable, sortable, WYSIWYG (tinyMCE-enabled) text editors complete with media buttons.  And as a bonus, it shows a single field using wp_editor() because that also needed a little twist to work with WPA.

Dimas seems to recommend putting the WP Alchemy core files in /wp-content so they are not included in my theme.  You’ll need to do that (or change my theme to include the WPA class elsewhere), and then simply activate the theme and add a new post to see the boxes in action.  For the curious, and come on you know you are, the real magic is in the kia-metabox.js script.

Download the sample theme from for an idea of how it works:

Download876 downloads

Fork me on github!  Perhaps we can figure out how to use the quicktags editor when the visual editor is disabled.

Full tutorial to come…  maybe.

This entry was posted in Tutorial and tagged , , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

58 Comments

  1. Posted March 13, 2012 at 7:03 pm | Permalink

    Great work.
    I’ve just tested this out and it works a treat!
    Still messing around but so far it does the business without a hiccup.

  2. Posted March 18, 2012 at 5:19 pm | Permalink

    OH YEAH!! This is really amazing. I’d just stumbled onto WPAlchemy (which is also really awesome) and have been sinking tons of hours trying to get these visual editors to work with the media upload button. Found this a few hours ago but was avoiding actually cracking it open — too lazy to install and switch themes. Finally did and at first the images weren’t finding the field to load into, then I realized I still had the Custom Field Template Plugin installed and that javascript must have been competing somehow. Deleted CFT Plugin — won’t be needing it anymore. It works amazing now.
    Thanks for all the hard work and diligent documentation and sharing.

  3. Posted March 18, 2012 at 5:40 pm | Permalink

    Now all I really need to do is figure out how to get each editor to pick up the tinyMCE customization i’ve created in my functions file. I’ll let you know how it goes. Thanks again!
    - sry for the multiple personalities, just got my gravatar squared away for this email

    • kathy
      Posted March 18, 2012 at 5:56 pm | Permalink

      in theory, it should be using the same tinyMCE editor parameters as the main editor (unless you put a minimal class on the customEditor div)… i haven’t had any problems with the repeating boxes showing custom buttons. is this not working for you?

      glad you finally got over the reluctance to switch themes. i made it this way so that it’d be easy to see the proof of concept and because it should be relatively easy to merge my “theme” on to yours. cheers!

      • Posted March 18, 2012 at 7:55 pm | Permalink

        Oh derf – you’re right. That customization is in my other theme’s functions file. Once I’ve merged it all together its working great. Very, very impressed. This is such a useful add on to using WordPress as a CMS. Thanks again.

      • Posted March 19, 2012 at 2:59 pm | Permalink

        I was having trouble with elements that had custom classes applied from my customized tinyMCE. They would always somehow generate an extra empty p tag or line break as they loaded into the textareas on my edit screen. They were saving to the database fine, though, but only the first time since the second save would have thoseptags and line breaks in the form field. I fixed it by changing the order of the functions applied to $mb->get_the_value() as its loaded into the textarea.

        echo esc_html( wp_richedit_pre($mb->get_the_value()) );
        became:
        echo wp_richedit_pre(esc_html( $mb->get_the_value()) );

        - Hope the code above displays correctly, if not sry.

        • kathy
          Posted March 19, 2012 at 3:02 pm | Permalink

          spencer, do you have an example of the type of classes that you are using? just so i can experiment and see the difference between the two… i think you can put code between some pre tags? i should fix my damned blog at some point

  4. Posted March 19, 2012 at 4:00 pm | Permalink

    Well, the plot thickens. I’ll have to delete or edit the previous comment because though it seems to work for the following example text:
    Quote Title 1″A paragraph that is also a quote. And has a class name that applies a border-bottom”Quote Title 2″Another paragraph that is a quote.”

    It also removes important breaks and ptags in the following:
    A Person Job TitleDegree, school Degree, School divider

    So far, it seems that applying the wp_richedit_pre function to text from the database as it is fed to the textarea on the edit screen does great stuff for keeping wanted ptags and breaks, except when there’s a defined class in the element. Then it seems to generate an empty p tag.

    I’ll keep investigating and check back here in case you have any thoughts.

    • kathy
      Posted March 19, 2012 at 4:21 pm | Permalink

      curious. i don’t have time to check into this today, but will try to look at it soon. do keep me posted. i think i named this aptly as the complete solution might never be found. is there some reason you aren’t using repeating groups of text inputs if each group (Assuming) follows the person/job/title/degree/ format?

      • Posted March 19, 2012 at 6:08 pm | Permalink

        Sadly the edit panel I’m using this for is much more complicated than one repeating field. Overall, there are three my_meta_control divs, one for each section of the layout on the viewer side. Each my_meta_control has a field group that is repeatable and sortable — thanks to your wonderful work here.
        It all works like a charm now, except for that one snag with classes applied to paragraphs in the tinyMCE textareas. I needed to figure this out to allow the user the most amount of flexibility with the type of content they can place in each field.

        Good news is I have a very, very dirty but seemingly effective fix. Instead of:

        echo esc_html( wp_richedit_pre($mb->get_the_value()) );

        to populate my textareas on the edit screen, I’m using:

        echo str_replace(‘><br />’, ‘>’, esc_html( wp_richedit_pre($mb->get_the_value()) ));

        This is grabbing all the break tags that occur just after any other element’s close and removing them. These are what seem to get converted into empty ptags by javascript in the textarea, which then get saved to the database. I know its probably overkill and an inappropriate place to address the actual issue I’m having, but it’s seeming to work well so far.

        Again thanks for all your help and work and I’ll keep you posted if I find a better fix.

  5. Posted March 19, 2012 at 4:01 pm | Permalink

    oops, those pre tags didn’t seem to work. Sorry

  6. Posted March 26, 2012 at 10:10 am | Permalink

    Has anyone else noticed issues with characters & symbols? I’ve found that the £ symbol doesn’t work correctly when saved and is output as a broken character. Had to switch to html view and manually type £ instead.

    • kathy
      Posted March 27, 2012 at 9:22 pm | Permalink

      one more thing to look into i guess. if you find a solution.. post it at github.

      • Posted March 28, 2012 at 9:36 am | Permalink

        I’ve just tested the issue with the holy grail theme and I still get the issue, but not on the repeating text box. What is the difference between the two?

        • kathy
          Posted March 28, 2012 at 12:44 pm | Permalink

          i really wish i could say what the difference is. i can only guess that something in the way alchemy saves data is different? but there does seem to be a difference. for instance, in displaying the value of the textarea the wp_editor takes the value straight from the DB, but the repeating fields need to be decoded.

  7. Posted March 27, 2012 at 9:09 pm | Permalink

    Hey Kathy -

    Thank you so much for working this out. It’s fan-freakin’-tastic. Quick question though; how would you go about utilizing the_excerpt() for the multiple fields? For now I just enabled support for excerpts in the post type, however I’d like it to act more intuitively (hence the want for meta boxes, right?). I’d appreciate your input. Thanks!

    Bryan

    • kathy
      Posted March 27, 2012 at 9:26 pm | Permalink

      hi bryan! you’re very welcome. it isn’t perfect, but it is a pretty workable solution i think for most. you want to create excerpts for the meta fields? the_excerpt and get_the_excerpt are specific to the post’s main excerpt, but if you want to shorten the text in the metaboxes then you could try outputting it

      wp_trim_excerpt($text)

      see: http://codex.wordpress.org/Function_Reference/wp_trim_excerpt

      but excerpts will strip all the html that we just worked so hard to add with the tinyMCE boxes so i’m confused as to why you’d want to. thanks for stopping by! cheers!

      • Posted March 27, 2012 at 9:42 pm | Permalink

        Who’s looking for perfect? ;)

        I wasn’t aware of the excerpt stripping out HTML; I will keep that in mind. What I needed it for what just a little “teaser” text that would be placed in a sidebar and lead the website visitor to the main content—which would be nicely formatted but the HTML. :)

        Thanks again!

        B

  8. Posted March 28, 2012 at 9:52 am | Permalink

    If you have charset problems please change.
    metaboxes/single-texarea.php and metaboxes/repeating-texarea.php
    $val = html_entity_decode($mb->get_the_value());
    to this
    $val = html_entity_decode($mb->get_the_value(), ENT_QUOTES, 'UTF-8');

    it will solve your problem.

    • Posted March 28, 2012 at 12:28 pm | Permalink

      Brilliant! That did the trick.
      Thanks.

    • kathy
      Posted March 28, 2012 at 12:42 pm | Permalink

      great! thanks for that. i will have to add it to the “grail”. i also took another crack at the quicktags html editor, which seems to work on one hook, but not on the later hook that we need to ‘borrow’ the tinymce settings.

    • Posted April 10, 2013 at 12:45 am | Permalink

      Yo you are awesome, thank you!

  9. Posted April 4, 2012 at 9:13 pm | Permalink

    Has anyone figured out how to get the wp_editor() fully working when inserting into the DOM via javascript?

    • kathy
      Posted April 4, 2012 at 9:16 pm | Permalink

      afaik, no. and i’ve tried too. the thing is that wp_editor() is a server-side function that needs to have an ID passed to it to function. the repeating boxes created w/ alchemy don’t exist yet, and their IDs are created client-side using javascript.

      • Posted April 4, 2012 at 9:22 pm | Permalink

        I am using wp_editor() via WordPress’s ajax call tho. So it creates the id from the server side instead of javascript side. Javascript is just inserting the html produced. It loads the editor but you can not switched between visual and html tab.

        • kathy
          Posted April 4, 2012 at 9:30 pm | Permalink

          well that’s quite clever. can you post your code somewhere? a gist? or pastebin?

          • Posted April 4, 2012 at 9:35 pm | Permalink

            I will work on that. I have to extract it from the project a bit.

  10. Posted April 8, 2012 at 5:11 pm | Permalink

    This is all such great stuff! Great work, and thanks so much for all of the time that has been put into this. It’s changed how I look at the WP dashboard for sure.
    Quick question, and to understand you all correctly (I know enough of this stuff to be dangerous, but some of the technical aspects are still a little over my head!)
    I also have had trouble when switching between the visual and html editors if i make ‘hide-editor’ -> false
    It occurred to me that this is probably why you have it set to ‘true’ in the example files, as switching back and forth does add the extra tags as noted in the comments.
    Do you think it’s best (ie. most stable) to simply just be keep it as ‘false’, and not incorporate the default editor panel, or am I just missing one of the above posted workarounds.
    Thanks!

  11. Posted May 9, 2012 at 1:45 pm | Permalink

    Hi Kathy,

    Thank you for sharing your work!
    Found one issue though. When sorting the text areas, it removes any p tags from the content of the dragged text area.

    Don’t know if this is related to your changes or to the wpalchemy class or even wordpress itself.

    Does this happens to you?

    Thanks,
    Nelson

    • kathy
      Posted May 9, 2012 at 2:15 pm | Permalink

      i’ll have to look into that, though i can’t promise when since i am busy with another project at the moment. wordpress doesn’t actually save save p tags in the database. tinymce pretends to use them and then the wp_autop automatically adds them on the front end (including to the meta content if you are using my code which has a wp_autop added to the meta_content filter. are you manually adding extra p tags?

  12. Posted May 10, 2012 at 11:26 am | Permalink

    Hi Kathy,

    It seems it’s known a bug related to TinyMCE which cannot be moved around in the DOM or it will break.

    The solution to this is to not allow drag n’ drop at all.

    Cheers,
    Nelson

    • kathy
      Posted June 1, 2012 at 1:06 am | Permalink

      Yes that is a known bug. In my mind, the end solution will be to dump tinyMCE for good and use a different editor, but that is a long ways away. But for now, I mostly got around this by turning tinyMCE off on drag, and then re-initializing it when the drop was complete. this works within the metabox, but could well (and probably does) break if you move the entire metabox. But how often does that happen?

      • Posted June 1, 2012 at 9:13 am | Permalink

        In my case I was developing a custom post type with repeatable fields that have no defined order and it could be useful to move them around instead of deleting and creating it all over again.

  13. Jay
    Posted June 7, 2012 at 1:05 pm | Permalink

    Hi Kathy,

    I need help on how to display the values on multiple fields.

    Here is my code. It only shows blank on the template….

    https://gist.github.com/21d0e399e686479a7441

    You can see the screenshot here http://screencast.com/t/8LSbfsLjCcFO

    Please help me I’ve been figuring this out for a week and I can’t get it to display the values.

    Thanks!

    Jay

  14. Posted June 9, 2012 at 7:55 pm | Permalink

    Ran into a potential problem .
    Changing the WP and Site address seemed to make all of the entered data go away…

    I installed and set up content and the fields on a WP installation in a directory (and a temporary IP) … when it was all set, I made it live by changing switched that to the proper domain name, and made the site address the root folder.

    All of the data moved over just fine EXCEPT the stuff that was done with this. Not a huge deal, since I only used it on one page… but perhaps something simple got messed up. Any thoughts? or is this a known issue to be aware of?

    • Posted June 20, 2012 at 12:24 am | Permalink

      wow, this is not something that i have seen, but then, i haven’t really tried it. like everything else with Alchemy, all your data should be stored in the postmeta table and be associated with the post, by it’s post ID. so i know it doesn’t answer your question, but i really can’t think of a reason why the data wouldn’t migrate.

      • Posted June 26, 2012 at 11:01 am | Permalink

        Had same problem (with heavy usage of WPAlchemy). It’s apparently caused by serialized data using the hosts url’s character length. So where a find and and replace in the SQL might ordinarily work when migrating, a url with a different char length seems to effect the pulling in of the serialized data. Tried few solutions but this was most reliable: http://wordpress.org/extend/plugins/wp-migrate-db/

  15. Boy Wonder Shawn
    Posted August 22, 2012 at 11:36 am | Permalink

    Kathy, I’ve followed your work since I first began using Dimas’ WP Alchemy a year ago. And I have a secret, whenever I find myself in a fix, I comb through the comments to see what “Kathy said/did”.

    Anyways, I was stuck on what I thought was the impossible, and I thought to myself WWKD?

    Wing and prayer I googled and guess what – Kathy did the impossible!

    You’re pretty awesome, but I think the word the kids are using these days is “fresh”.

    KATHY IS FRESH FOLKS!!!

    Thanks for your hard work, but most importantly your sharing.

    I’ll show you what I’ve made after I make it!

    • Posted August 22, 2012 at 1:27 pm | Permalink

      Wow, what a nice comment to wake up to! Thank you for your kind words! Though fresh is totally what my grandmother called me when I was being snotty. ;) I look forward to seeing what you make w/ Alchemy. If you’ve read the comment on this post then you’ll know that there is still an issue or 2… I’m not actively working on this at the moment, so if you solve those send me a pull request at git or just a note or whatever. Thanks for stopping by!

  16. John
    Posted October 4, 2012 at 9:50 pm | Permalink

    It’s true people…. Kathy IS awesome. Thank you for working out all the big problems on this before I knew they existed. I had been visualizing repeating WYSIWYG editors for a while but when I sat down to make it actually happen, you made it much easier and added the media upload for each as a bonus. Well played!

    • Posted October 4, 2012 at 10:13 pm | Permalink

      Thanks for the compliment John! I’m glad you found it helpful. There are still a few bugs, but it is a lot closer than anything else I was able to find.

  17. Klara
    Posted October 12, 2012 at 7:41 pm | Permalink

    I tried the #8 solution for the character-problem but I couldnt get it working. I could only find that string of text in the single-textarea.php not in the repeating.

    The first save went smooth, if I update I get questionmarks all over.. I would be very grateful for some input.

    • Posted October 12, 2012 at 8:05 pm | Permalink

      Hi Klara, thanks for stopping by. I don’t really understand your question… what exactly is happening? Credit this to my ignorance of not needing to use any special characters in English. Also, I am not actively developing this so I can’t promise I will come up with a solution.

  18. Klara
    Posted October 13, 2012 at 9:04 am | Permalink

    Hi Kathy!
    Thankyou for your quick respons!

    If I save the metabox first I get this.
    http://thesubjectiveguide.com/screen1.png
    All nice and clean.

    Though it looks like this in the admin:
    http://thesubjectiveguide.com/screen2.png

    If I later update the post it will look like this.
    http://thesubjectiveguide.com/screen3.png

    This didnt happen when I didnt have the edit-bar above, just using plain simple-meta from WPAlchemy.

    • Posted October 13, 2012 at 2:59 pm | Permalink

      Klara, Ok I see what you are saying now. Are you having issues with a single textarea? Or the repeating textareas? I just tried the character-encoding solution from comment #8 and it seems to work for single textareas, can you try it again now that I have edited the apostrophe style of the posted code? I cannot duplicate a problem with multiple textareas.

  19. Klara
    Posted October 14, 2012 at 5:21 pm | Permalink

    That did the trick actually! Thanks!

  20. Posted November 7, 2012 at 6:10 pm | Permalink

    This is amazing. Thank you so much for all of your hard work!

    • Posted November 7, 2012 at 7:04 pm | Permalink

      You’re welcome! Thanks for leaving a comment. It’s cool to know that people are still finding this useful.

  21. Posted February 9, 2013 at 2:04 pm | Permalink

    Thanks a lot for this code. It works perfectly.
    You made my day shiny ;)

    • Posted February 9, 2013 at 3:00 pm | Permalink

      Does this still work with the new media uploader in WP 3.5? I probably need to update things but just don’t have the time. Also, I hope that shiny days means you are a Firefly fan!

      • Posted February 18, 2013 at 5:17 pm | Permalink

        The Media Uploader works for me in WP 3.5 and everything else works just great, thanks a lot! :)

        • Posted February 18, 2013 at 5:25 pm | Permalink

          You’re welcome! and thanks for the confirmation that it all still works with WP3.5.

  22. Posted February 11, 2014 at 4:33 am | Permalink

    I have been reading the above article. It is explained very well.

    Thanks

  23. Bhavesh Vaghela
    Posted February 28, 2014 at 4:59 pm | Permalink

    WordPress 3.9 is going to upgrade tinymce to 4.x.
    and javascript code breaks in it.
    I have modified your javascript so it works with tinymce 4.x in wp 3.9
    tinymce 4.x in wordpress 3.9

    Hope It will be helpful to others.
    http://wp-lovers.com/wpquestions/testplugin-new.zip

    • Posted February 28, 2014 at 8:24 pm | Permalink

      You wouldn’t maybe want to submit a pull request on Github would you? That’s be extra cool. ;) I will check it out when I can. Thanks!

  24. Angela
    Posted April 23, 2014 at 9:28 am | Permalink

    Hi Kathy…well done with getting this working so well…I could do with a little pointer in the right direction…i’ve copied your code from the content-single template into my own and added the core alchemy class and the functions in the functions.php..within admin everything looks great…i can enter into the editors and they save..but I can’t see anything on the actual viewable page…i know i must be missing something really simple here…i would really appreciate any advice…thanks Ang

    • Posted April 23, 2014 at 11:47 am | Permalink

      Thanks Angela. It is really hard to say what could be going wrong for you. Double-check that you are editing the correct theme, are globally declaring the metabox variable:

      global $simple_textarea, $repeating_textareas;

      And try turning on WP_DEBUG. Good luck.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This site's anti-spam requires Javascript; enable it and refresh this page to continue.

NoScript Users: Whitelist the domain services.wpspamhammer.com and refresh.