Add WYSIWYG editor in WordPress comments (without plugin)

wordpress-kommentare-editor

By default, WordPress comments can only be written as plain text. I’ll show you how to add a WYSIWYG editor so visitors can format their comments.

Pure text is sometimes not enough to express more complicated concerns in a comment, to highlight words or to link. For this purpose there are so-called WYSIWYG editors (WYSIWYG stands for “What You See Is What You Get”) or rich text editors. You know this visual editing/formatting of text e.g. from Word or similar programs. By default, WordPress comments can only be written as plain text.

With a few simple steps you can get the editor into your blog!

This is what WordPress comments look like by default:

WordPress standard comment function (plain text)
WordPress standard comment function (plain text)

And this is how your WordPress comments will look like in a few minutes 😉

WordPress Kommentarfunktion mit Editor (unser Endgergebnis)
WordPress Kommentarfunktion mit Editor (unser Endgergebnis)

The best demo is if you scroll down to the comments and try it yourself. I have programmed the editor in this post:

Program your own WYSIWYG Editor

1. Create Child Theme

In the first step you should (if already done jump directly to step 2) create a child theme of your current theme. This prevents that after a theme update all your changes are gone again.

  • Navigate to your themes folder under wp-content/themes
  • Create a new folder named like the folder of your used theme, only with the extension “-child”
    Example: Theme used: oceanwp, then create a folder oceanwp-child
  • In the newly created folder, create a file named style.css
  • Paste the following content there and replace the value at Template with your theme name:
/*
 Theme Name:   Your custom Child theme
 Template:     oceanwp
*/
  • Now go to Design > Themes in the backend and activate the theme you just created. In this case there is the entry “Your custom Child theme”.

2. Remove default comment editor

To remove the old WordPress comment editor we need to edit comments.php. Copy this file from your themes folder into your child theme.

Search there for a line that contains the word comment_field. It should look something like this for you:

// [...]
// Comment form args.
$args = array(
    /* translators: 1: logged in to comment */
    'must_log_in'          => '<p class="must-log-in">' . sprintf(esc_html__('You must be %1$slogged in%2$s to post a comment.', 'oceanwp'), '[...],
    'logged_in_as'         => '<p class="logged-in-as">' . esc_html__('Logged in as', 'oceanwp') . ' <a href="' . admin_url('profile.php') . '[...],
    'comment_notes_before' => false,
    'comment_notes_after'  => false,
    // 'comment_field'        => '<div class="comment-textarea"><label for="comment" class="screen-reader-text">' . esc_html__('Comment', 'ocea[...],
    'id_submit'            => 'comment-submit',
    'label_submit'         => esc_html(oceanwp_theme_strings('owp-string-comment-post-button', false, 'oceanwp')),
);
// [...]

Comment out the corresponding line as shown in the example.

3. Create & customize new comment editor in WordPress

In another post I showed how to program your own WYSIWYG editor using HTML, CSS and JavaScript. We will use this editor here.

We also use a WordPress filter comment_form_defaults. This allows us to refill the comment_field variable that we commented out in the last step.

To do this, I put all the components together in a file called wysiwyg-comments.php and put it in the child theme:

<?php

add_filter('comment_form_defaults', 'wysiwyg_webdeasy_editor');
function wysiwyg_webdeasy_editor($args) {
    ob_start();
?>

    <div class="wp-webdeasy-comment-editor">
        <div class="toolbar">
            <div class="line">
                <div class="box">
                    <span class="editor-btn icon smaller" data-action="bold" data-tag-name="b" title="Bold">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/bold.png" />
                    </span>
                    <span class="editor-btn icon smaller" data-action="italic" data-tag-name="i" title="Italic">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/italic.png" />
                    </span>
                    <span class="editor-btn icon smaller" data-action="underline" data-tag-name="u" title="Underline">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/underline.png" />
                    </span>
                    <span class="editor-btn icon smaller" data-action="strikeThrough" data-tag-name="strike" title="Strike through">
                        <img src="https://img.icons8.com/fluency-systems-filled/30/000000/strikethrough.png" />
                    </span>
                </div>
                <div class="box">
                    <span class="editor-btn icon has-submenu">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-left.png" />
                        <div class="submenu">
                            <span class="editor-btn icon" data-action="justifyLeft" data-style="textAlign:left" title="Justify left">
                                <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-left.png" />
                            </span>
                            <span class="editor-btn icon" data-action="justifyCenter" data-style="textAlign:center" title="Justify center">
                                <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-center.png" />
                            </span>
                            <span class="editor-btn icon" data-action="justifyRight" data-style="textAlign:right" title="Justify right">
                                <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-right.png" />
                            </span>
                            <span class="editor-btn icon" data-action="formatBlock" data-style="textAlign:justify" title="Justify block">
                                <img src="https://img.icons8.com/fluency-systems-filled/48/000000/align-justify.png" />
                            </span>
                        </div>
                    </span>
                    <span class="editor-btn icon" data-action="insertOrderedList" data-tag-name="ol" title="Insert ordered list">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/numbered-list.png" />
                    </span>
                    <span class="editor-btn icon" data-action="insertUnorderedList" data-tag-name="ul" title="Insert unordered list">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/bulleted-list.png" />
                    </span>
                    <span class="editor-btn icon" data-action="outdent" title="Outdent" data-required-tag="li">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/outdent.png" />
                    </span>
                    <span class="editor-btn icon" data-action="indent" title="Indent">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/indent.png" />
                    </span>
                </div>
                <div class="box">
                    <span class="editor-btn icon" data-action="insertHorizontalRule" title="Insert horizontal rule">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/horizontal-line.png" />
                    </span>
                </div>
            </div>
            <div class="line">
                <div class="box">
                    <span class="editor-btn icon smaller" data-action="undo" title="Undo">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/undo--v1.png" />
                    </span>
                    <span class="editor-btn icon" data-action="removeFormat" title="Remove format">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/remove-format.png" />
                    </span>
                </div>
                <div class="box">
                    <span class="editor-btn icon smaller" data-action="createLink" title="Insert Link">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/add-link.png" />
                    </span>
                    <span class="editor-btn icon smaller" data-action="unlink" data-tag-name="a" title="Unlink">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/delete-link.png" />
                    </span>
                </div>
                <div class="box">
                    <span class="editor-btn icon" data-action="toggle-view" title="Show HTML-Code">
                        <img src="https://img.icons8.com/fluency-systems-filled/48/000000/source-code.png" />
                    </span>
                </div>
            </div>
        </div>
        <div class="content-area">
            <div class="visuell-view" contenteditable></div>
            <textarea class="html-view" id="comment" name="comment"></textarea>
        </div>
    </div>
    <div class="modal">
        <div class="modal-bg"></div>
        <div class="modal-wrapper">
            <div class="close">✖</div>
            <div class="modal-content" id="modalCreateLink">
                <h3>Insert Link</h3>
                <input type="text" id="linkValue" placeholder="Link (example: https://webdeasy.de/)" />
                <div class="row">
                    <input type="checkbox" id="new-tab" />
                    <label for="new-tab">Open in new Tab?</label>
                </div>
                <button class="done">Done</button>
            </div>
        </div>
    </div>
    <script>
        // define vars
        const editor = document.getElementsByClassName('wp-webdeasy-comment-editor')[0];
        const toolbar = editor.getElementsByClassName('toolbar')[0];
        const buttons = toolbar.querySelectorAll('.editor-btn:not(.has-submenu)');
        const contentArea = editor.getElementsByClassName('content-area')[0];
        const visuellView = contentArea.getElementsByClassName('visuell-view')[0];
        const htmlView = contentArea.getElementsByClassName('html-view')[0];
        const modal = document.getElementsByClassName('modal')[0];

        // add active tag event
        document.addEventListener('selectionchange', selectionChange);

        // add paste event
        visuellView.addEventListener('paste', pasteEvent);

        // add paragraph tag on new line
        contentArea.addEventListener('keypress', addParagraphTag);

        // add toolbar button actions
        for (let i = 0; i < buttons.length; i++) {
            let button = buttons[i];

            button.addEventListener('click', function(e) {
                let action = this.dataset.action;

                switch (action) {
                    case 'toggle-view':
                        execCodeAction(this, editor);
                        break;
                    case 'createLink':
                        execLinkAction();
                        break;
                    default:
                        execDefaultAction(action);
                }

            });
        }

        /** 
         * This function toggles between visual and html view
         */
        function execCodeAction(button, editor) {

            if (button.classList.contains('active')) { // show visuell view
                visuellView.innerHTML = htmlView.value;
                htmlView.style.display = 'none';
                visuellView.style.display = 'block';

                button.classList.remove('active');
            } else { // show html view
                htmlView.innerText = visuellView.innerHTML;
                visuellView.style.display = 'none';
                htmlView.style.display = 'block';

                button.classList.add('active');
            }
        }

        /**
         * This function adds a link to the current selection
         */
        function execLinkAction() {
            modal.style.display = 'block';
            let selection = saveSelection();

            let submit = modal.querySelectorAll('button.done')[0];
            let close = modal.querySelectorAll('.close')[0];

            // done button active => add link
            submit.addEventListener('click', function(e) {
                e.preventDefault();
                let newTabCheckbox = modal.querySelectorAll('#new-tab')[0];
                let linkInput = modal.querySelectorAll('#linkValue')[0];
                let linkValue = linkInput.value;
                let newTab = newTabCheckbox.checked;

                restoreSelection(selection);

                if (window.getSelection().toString()) {
                    let a = document.createElement('a');
                    a.href = linkValue;
                    if (newTab) a.target = '_blank';
                    window.getSelection().getRangeAt(0).surroundContents(a);
                }

                modal.style.display = 'none';
                linkInput.value = '';

                // deregister modal events
                submit.removeEventListener('click', arguments.callee);
                close.removeEventListener('click', arguments.callee);
            });

            // close modal on X click
            close.addEventListener('click', function(e) {
                e.preventDefault();
                let linkInput = modal.querySelectorAll('#linkValue')[0];

                modal.style.display = 'none';
                linkInput.value = '';

                // deregister modal events
                submit.removeEventListener('click', arguments.callee);
                close.removeEventListener('click', arguments.callee);
            });
        }

        /**
         * This function executes all 'normal' actions
         */
        function execDefaultAction(action) {
            document.execCommand(action, false);
        }

        /**
         * Saves the current selection
         */
        function saveSelection() {
            if (window.getSelection) {
                sel = window.getSelection();
                if (sel.getRangeAt && sel.rangeCount) {
                    let ranges = [];
                    for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                        ranges.push(sel.getRangeAt(i));
                    }
                    return ranges;
                }
            } else if (document.selection && document.selection.createRange) {
                return document.selection.createRange();
            }
            return null;
        }

        /**
         *  Loads a saved selection
         */
        function restoreSelection(savedSel) {
            if (savedSel) {
                if (window.getSelection) {
                    sel = window.getSelection();
                    sel.removeAllRanges();
                    for (var i = 0, len = savedSel.length; i < len; ++i) {
                        sel.addRange(savedSel[i]);
                    }
                } else if (document.selection && savedSel.select) {
                    savedSel.select();
                }
            }
        }

        /**
         * Sets the current selected format buttons active/inactive
         */
        function selectionChange(e) {

            for (let i = 0; i < buttons.length; i++) {
                let button = buttons[i];

                // don't remove active class on code toggle button
                if (button.dataset.action === 'toggle-view') continue;

                button.classList.remove('active');
            }

            if (!childOf(window.getSelection().anchorNode.parentNode, editor)) return false;

            parentTagActive(window.getSelection().anchorNode.parentNode);
        }

        /**
         * Checks if the passed child has the passed parent
         */
        function childOf(child, parent) {
            return parent.contains(child);
        }

        /**
         * Sets the tag active that is responsible for the current element
         */
        function parentTagActive(elem) {
            if (!elem || !elem.classList || elem.classList.contains('visuell-view')) return false;

            let toolbarButton;

            // active by tag names
            let tagName = elem.tagName.toLowerCase();
            toolbarButton = document.querySelectorAll(`.toolbar .editor-btn[data-tag-name="${tagName}"]`)[0];
            if (toolbarButton) {
                toolbarButton.classList.add('active');
            }

            // active by text-align
            let textAlign = elem.style.textAlign;
            toolbarButton = document.querySelectorAll(`.toolbar .editor-btn[data-style="textAlign:${textAlign}"]`)[0];
            if (toolbarButton) {
                toolbarButton.classList.add('active');
            }

            return parentTagActive(elem.parentNode);
        }

        /**
         * Handles the paste event and removes all HTML tags
         */
        function pasteEvent(e) {
            e.preventDefault();

            let text = (e.originalEvent || e).clipboardData.getData('text/plain');
            document.execCommand('insertHTML', false, text);
        }

        /**
         * This functions adds a paragraph tag when the enter key is pressed
         */
        function addParagraphTag(evt) {
            if (evt.keyCode == '13') {

                // don't add a p tag on list item
                if (window.getSelection().anchorNode.parentNode.tagName === 'LI') return;
                document.execCommand('formatBlock', false, 'p');
            }
        }

        /**
         * On WordPress comment form submit: set last content to html view
         */
        const commentForm = document.getElementById('commentform');
        commentForm.addEventListener('submit', function(e) {
            htmlView.innerText = visuellView.innerHTML;
        });
    </script>
    <style>
        /* WYSIWYG Editor */
        .wp-webdeasy-comment-editor {
            width: 100%;
            min-height: 30rem;
            box-shadow: 0 0 4px 1px rgba(0, 0, 0, 0.3);
            border-top: 6px solid #4a4a4a;
            border-radius: 3px;
            margin: 2rem 0;
        }

        .wp-webdeasy-comment-editor .toolbar {
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
        }

        .wp-webdeasy-comment-editor .toolbar .line {
            display: flex;
            border-bottom: 1px solid #e2e2e2;
        }

        .wp-webdeasy-comment-editor .toolbar .line:last-child {
            border-bottom: none;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box {
            display: flex;
            border-left: 1px solid #e2e2e2;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn {
            display: block;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            transition: 0.2s ease all;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn:hover,
        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn.active {
            background-color: #e1e1e1;
            cursor: pointer;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn.icon img {
            width: 15px;
            padding: 9px;
            box-sizing: content-box;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn.icon.smaller img {
            width: 16px;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn.has-submenu {
            width: 20px;
            padding: 0 10px;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn.has-submenu::after {
            content: '';
            width: 6px;
            height: 6px;
            position: absolute;
            background-image: url(https://img.icons8.com/ios-glyphs/30/000000/chevron-down.png);
            background-repeat: no-repeat;
            background-size: cover;
            background-position: center;
            right: 4px;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn.has-submenu .submenu {
            display: none;
            position: absolute;
            top: 34px;
            left: -1px;
            z-index: 10;
            background-color: #FFF;
            border: 1px solid #b5b5b5;
            border-top: none;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn.has-submenu .submenu .btn {
            width: 39px;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn.has-submenu .submenu:hover {
            display: block;
        }

        .wp-webdeasy-comment-editor .toolbar .line .box .editor-btn.has-submenu:hover .submenu {
            display: block;
        }

        .wp-webdeasy-comment-editor .content-area {
            padding: 15px 12px;
            line-height: 1.5;
        }

        .wp-webdeasy-comment-editor .content-area .visuell-view {
            outline: none;
            min-height: 12rem;
        }

        .wp-webdeasy-comment-editor .content-area .visuell-view p {
            margin: 12px 0;
        }

        .wp-webdeasy-comment-editor .content-area .html-view {
            outline: none;
            display: none;
            width: 100%;
            height: 200px;
            border: none;
            resize: none;
        }

        /* Modal */
        .modal {
            z-index: 40;
            display: none;
        }

        .modal .modal-wrapper {
            background-color: #FFF;
            padding: 1rem;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 20rem;
            min-height: 10rem;
            z-index: 41;
        }

        .modal .modal-wrapper .close {
            position: absolute;
            top: 1rem;
            right: 1rem;
            cursor: pointer;
        }

        .modal .modal-wrapper .modal-content {
            flex-direction: column;
        }

        .modal .modal-wrapper .modal-content h3 {
            margin-top: 0;
        }

        .modal .modal-wrapper .modal-content input {
            margin: 1rem 0;
            padding: 0.5rem;
        }

        .modal .modal-wrapper .modal-content input[type="text"] {
            width: calc(100% - 1rem);
        }

        .modal .modal-wrapper .modal-content .row label {
            margin-left: 0.5rem;
        }

        .modal .modal-wrapper .modal-content button {
            background-color: #D2434F;
            border: 0;
            color: #FFF;
            padding: 0.5rem 1.2rem;
            cursor: pointer;
        }

        .modal .modal-bg {
            position: fixed;
            background-color: rgba(0, 0, 0, 0.3);
            width: 100vw;
            height: 100vh;
            top: 0;
            left: 0;
        }
    </style>

<?php
    $args['comment_field'] = ob_get_clean();
    return $args;
}

Now we create another functions.php in the child theme and call our just created wysiwyg-comments.php there:

<?php
require_once(__DIR__ . "/wysiwyg-comments.php");

This is 1:1 the code from the WYSIWYG Editor Tutorial. Therefore, we still need to make three small adjustments to make it work properly in WordPress.

Note that the editor uses icons from Icons8 and you must include a note to that effect on your website.

3.1 Customize editor styling

I would like to have the editor take up full width and also be a bit taller. That’s why this code. You can of course customize everything according to your wishes, so that the editor fits the comments on your blog or website.

I have highlighted the exact location in red in the complete code above.

.wp-webdeasy-comment-editor {
  width: 100%;  // before: 40rem
  min-height: 30rem; // before: 18rem
  box-shadow: 0 0 4px 1px rgba(0, 0, 0, 0.3);
  border-top: 6px solid #4a4a4a;
  border-radius: 3px;
  margin: 2rem 0;
}

3.2 Customize HTML IDs to WordPress

The textarea of our HTML view needs the additional attributes name and id. In the complete code above I have highlighted the location.

<!-- Add 'name' and 'id' attribute -->
<textarea class="html-view" id="comment" name="comment"></textarea>

3.3 Pass HTML content when submitting form

In order for WordPress to also use the content from our editor, our HTML content must be placed in the text field used by WordPress when submitting the form.

To do this, this code must be inserted in the highlighted position in the code:

/**
 * On WordPress comment form submit: set last content to html view
 */
const commentForm = document.getElementById('commentform');
commentForm.addEventListener('submit', function(e) {
  htmlView.innerText = visuellView.innerHTML;
});

If you want, you can package the JavaScript and CSS into individual files and include them via wp_enqueue_script() and wp_enqueue_style() in functions.php.

That’s it. The editor is ready for use! 🙂 If there were any problems, feel free to write me a comment.

I have a complete post on quite a few interesting WordPress code snippets that can improve your site with little effort. Maybe this is interesting for you.

Related Posts
Join the Conversation

10 Comments

  1. Mauri says:

    just testing the format <3

  2. Mauro says:

    Does this support Ajax posting of comments?

    1. Lorenz says:

      In general you can use this editor with AJAX. But this tutorial provides a solution without AJAX.

  3. Ben Finn says:

    In my template, I’ve got just a plain comment_form() with no args. I’ve inserted all the code you provided, but my comment form looks exactly the same. I inspected the textarea, and the html-view class isn’t showing up.Do I need to expand the comment_form() somehow to ensure the filter operates properly?

    1. Lorenz says:

      Maybe there’s another comment_form_defaults hook in your template that overrides your changes. What theme do you use?

    2. TAGA says:

      <?php
      require_once(__DIR__ . "/wysiwyg-comments.php");

  4. Paul says:

    Nice Tutorial, I love it! But what if a user typed in an html tag, home the browser will render it as a text and not as other tags on the page.

Your email address will not be published. Required fields are marked *

bold italic underline strikeThrough
insertOrderedList insertUnorderedList outdent indent
removeFormat
createLink unlink
code

This can also interest you