How To Add the TinyMCE Visual Editor To The Comment Form in WordPress

| 24 Comments

TinyMCE visual editor in the comment form in WordPress
Seriously, how many ordinary people do you think understand the mysterious HTML codes, which can be used in the comment form on your blog? In the default themes included in WordPress below the comment form, you will find a cryptic message like this:

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>

If you want to provide your users some tools for formatting the content of their comments, why not give them a proper WYSIWYG editor? The one that is already built in to WordPress, namely TinyMCE, should be appropriate.

UPDATE April 26. 2014: Dariusz Lorek kindly made me aware of an update to the codebase of the TinyMCE integration with WordPress, which prevented this code snippet from working in the more recent versions. I have updated the snippet accordingly and now it works again. Thanks Dariusz!

Just copy and paste the following code snippet into the functions.php file in your theme:

<?php
add_filter( 'comment_form_field_comment', 'comment_editor' );

function comment_editor() {
	global $post;

	ob_start();

	wp_editor( '', 'comment', array(
		'textarea_rows' => 15,
		'teeny' => true,
		'quicktags' => false,
		'media_buttons' => false
	) );

	$editor = ob_get_contents();

	ob_end_clean();

	//make sure comment media is attached to parent post
	$editor = str_replace( 'post_id=0', 'post_id='.get_the_ID(), $editor );

	return $editor;
}

// wp_editor doesn't work when clicking reply. Here is the fix.
add_action( 'wp_enqueue_scripts', '__THEME_PREFIX__scripts' );
function __THEME_PREFIX__scripts() {
    wp_enqueue_script('jquery');
}
add_filter( 'comment_reply_link', '__THEME_PREFIX__comment_reply_link' );
function __THEME_PREFIX__comment_reply_link($link) {
    return str_replace( 'onclick=', 'data-onclick=', $link );
}
add_action( 'wp_head', '__THEME_PREFIX__wp_head' );
function __THEME_PREFIX__wp_head() {
?>
<script type="text/javascript">
	jQuery(function($){
		$('.comment-reply-link').click(function(e){
			e.preventDefault();
			var args = $(this).data('onclick');
			args = args.replace(/.*\(|\)/gi, '').replace(/\"|\s+/g, '');
			args = args.split(',');
			tinymce.EditorManager.execCommand('mceRemoveEditor', true, 'comment');
			addComment.moveForm.apply( addComment, args );
			tinymce.EditorManager.execCommand('mceAddEditor', true, 'comment');
		});
	});
</script>
<?php } ?>

Via | Translations: Danish

Author: Morten Brunbjerg Bech

Webdesigner, front end udvikler og bibliotekar. Arbejder primært med udvikling og design af Horsens Kommunes Bibliotekers webløsninger og er specialist i semantisk strukturering af webdokumenter samt Adobe Photoshop og Illustrator.

24 Comments

  1. That’s odd.

    I couldn’t say if this is the problem, but be sure to omit the beginning and ending < ?php ?> tags in this snippet if they are already in your functions.php.

  2. If paste all of this snippet into function.php of theme, do not work.
    if paste with omit <?php, (two), wordpress is not work

    • Hi,
      As it turns out, there have been some changes to the code base of TinyMCE editor integration in the more recent versions of WordPress. That seems to break this code snippet.

      However, its a very easy fix. Dariusz Lorek kindly notified me about it on Twitter.

      Just change mceRemoveControl/mceAddControl to mceRemoveEditor/mceAddEditor and you should be good to go. I’ll be updating this post accordingly.

  3. Do you know how to remove new Tinymce Menubar at the top ? This one with “file, edit, insert, view, format, table, tools”

    I know i can use Tinymce advanced plugin but this way i remove it for Admins too.
    I removed your teeny option and added toolbar1.
    ————————————————————————
    add_filter( ‘comment_form_defaults’, ‘rich_text_comment_form’ );
    function rich_text_comment_form( $args ) {
    ob_start();
    wp_editor( ”, ‘comment’, array(
    ‘media_buttons’ => false, // show insert/upload button(s) to users with permission
    ‘textarea_rows’ => ’10’, // re-size text area
    ‘tinymce’ => array(
    ‘menubar’ => ”,
    ‘toolbar1’ => ‘fontsizeselect,bold,italic,underline,strikethrough,bullist,numlist,alignleft,aligncenter,alignright,blockquote,link,unlink,|,undo,redo,media,image,emoticons,’,
    ‘toolbar2’ => ”, // 2nd row, if needed
    ‘toolbar3’ => ”, // 3rd row, if needed
    ‘toolbar4’ => ” // 4th row, if needed
    ),
    ‘quicktags’ => array(
    ‘buttons’ => ‘strong,em,link,block,del,ins,img,ul,ol,li,code,close’
    )
    ) );
    $args[‘comment_field’] = ob_get_clean();
    return $args;
    }
    ————————————————————————-

  4. very good
    thank you 🙂

  5. Almost….
    1. If you click to reply to a comment..then close the reply box (cancel).
    2. Then try to add a comment… the editor is ‘locked’. You cannot put the cursor back into the comment area.

    I’ll see if I can’t isolate the issue… as this is the closest I’ve found to a RTE editor in the WP comment area.

    Awesome work!! Let’s get it the rest of the way 🙂

    • Believe it is working. Seems as some strange CSS combination. Comments editor wrapper changes rules a bit. First had to put in my theme postion:relative; z-index:1; for comments input fields.

      Had also your problem and noticed text is colored white in text area and not visible, from
      .js .tmce-active .wp-editor-area.

    • Reload the page and it works again – but yeah; it would be good to fix this little bug!

  6. Works perfectly with later themes like twentyeleven.

    Unfortunately it won’t work if your theme ‘comments.php’ file is the old type.

    Here is a good comments.php to replace the old type (if yours doesn’t work):
    http://byronyasgur.wordpress.com/2011/09/09/51/

  7. It appears in my blog. But I can’t click in Name, Email, Website…field to fill it.

    Anyone can help me? My blog: http://portableappsviet.com/

    Thank you very much!

    • You need to have position:relative; and z-index:1; for your input fields.
      New comments wrapper change rules a bit.

      Same is for text area when you send comment. One class make text with white color. It is there, you can type you just dont see it. Override it in your theme csss.

      • Better separate and target (make new lines) classes for comment form, to not to influence input fields globally on website and posibly make other problems.

  8. // wp_editor doesn’t work when clicking reply. Here is the fix.

    How to do the same thing for this function?
    cancel_comment_reply_link

  9. For all people with non-clickable fields/area. it is not PHP code (directly) making this, but CSS. Use Firebug and it is easy to fix it.

  10. Honestly I haven’t tried but it appears that code is using old method “mceAddEditor”(Tinymce 3.x). However, Tinymce was updated to V4.x since WordPress 3.9 and it requires an update for creating tinymce object :

    tinymce.init({
    selector: ‘#textarea-id’,
    menubar : false,
    toolbar: “bold link”
    });

    Hope it helps

  11. Brilliant! Just what I needed. Why this isn’t WordPress’ default functionality I will never know.

  12. Hej Morten, thanks for sharing the code. I’m using it on this site: http://www.liniefuenf.de.

    It works 99% perfectly! I just noticed one detail: When the editor is in text mode and is moved due to a click on the “reply to comment” button, something strange happens: there seems to be a tinyMCE editor “inside” the plain html texarea. And it doesn’t dissappear even when I click the “cancel reply” button.

    Any idea how this problem can be solved? Is there a way to automatically switch to visual mode before the editor is moved?

  13. Pingback: Utiliser l'éditeur visuel TinyMCE dans les commentaires WordPress - b*web

  14. Thanks for this code snippet. It really helped me out! However, two things about the fix:

    1. It seems that it isn’t needed any more, because the code works well without it in WordPress 4.3.1. At least it does in my Stargazer theme.

    2. The fix screwed up the media loading page. It only showed a rotating circle, not being able to load any pictures.

    • Hi Kai LeRai

      Thanks. Well, this snippet is getting a bit old. It may be obsolete by now, I haven’t really been updating it lately. Maybe I ought to take another look at it.

      I’m not quite sure which media loading page you are referring to. Do you mean the attachment page? Can you throw me a link?

      • Hi Morten,

        thank you for your answer and sorry for the late reply. I just upgraded my server, tried your code again in its entirety to get some screenshots and suddenly it worked. May be I screwed up the first time when I copied it to my functions.php.

        Anyway, I also activated the text editor and while I was able to switch to it from the visual one, I wasn’t able to switch back. This happened with and without the fix. This might be related to my theme. I wasn’t able to test this with a different one. Just letting you know.

Leave a Reply