Aug 092016
 

So there are some plugins out there to hide and show WordPress comments (notably the one named “Hide Show Comment“), but there are some things I didn’t like about it.

  1. They want you to pay for more options (I’m quite frugal).
  2. There is no option to hide the comment form – only the comments.

So here’s how you do it. We’ll be using jQuery (JavaScript) and inserting the code with a plugin.

  1. Install a plugin that lets you insert custom code.
    1. SEO Ultimate can do this under the “Code Inserter” section (use the “Before Item Content section).
    2. Insert Headers and Footers can do this (use the “Scripts in Header” section)
  2. Insert the script below.
<script type="text/javascript">
    jQuery(function(){
            // make the "leave a comment" text hide/show the comment form.
            jQuery('.comment-reply-title').click(function(){
                jQuery('.comment-form').slideToggle('fast');
            });

            // hide the comment form by default
            jQuery('.comment-form').hide();

            // make the text look like a link so the user knows it's clickable.
            // return false means the page will not reload.
            jQuery('.comment-reply-title').wrap("<a href="" onclick="return false;" >");

            // the reply button should always show the comment form
            jQuery('.comment-reply-link').wrap("<a href="" onclick="jQuery('.comment-form').show();" >");

            // the cancel reply link should always hide the comment form
            jQuery('.cancel-comment-reply-link').wrap("<a href="" onclick="jQuery('.comment-form').hide();" >");
        });
</script>

That’s all you need really. The rest is just nitpicking. One issue is that the comment form is not hidden by default. If we simply add some CSS to fix it, then people who have JavaScript turned off will never see the comment form. So we want to hide the comment form by default only when JavaScript is supported.

    1. Add the following JavaScript to the header.
<script type="text/javascript">
document.documentElement.className = "js";
</script>
  1. Add the following custom CSS using a plugin or your theme (for example the plugin “Simple Custom CSS“).
/** hide the comment form only if JavaScript is enabled. */
.js .comment-form { display: none; }

The JavaScript-dependent CSS was taken from https://css-tricks.com/snippets/javascript/css-for-when-javascript-is-enabled/.