Skip to content
Advertisement

WordPress show/hide comments form

I have a problem with my wordpress theme. I can’t create a button to show/hide comments form.

I have a comments.php file with this code:

JavaScript

This file works properly but I can’t modify to add a button.

I try to change it in this way:

first I create new file comment_form.php with this code:

JavaScript

then modify comment.php in this way

JavaScript

But click on button result in: Fatal error: Call to undefined function comment_form()

So my question is: how to create a button to load wordpress comment_form() function only when clicked? I have few comments on my blog and I don’t want to load unnecessary code (like form and captcha) if it is not necessary.

Thanks

Advertisement

Answer

In my previous question I had two problems:

  • show / hide the comments form in wordpress posts
  • run the google recaptcha plugin only when needed (when the user wants to post a comment)

The solution adopted, from a logical point of view, is the following:

  • disable plugin used previously
  • default: hide wp comment form section through css
  • add button “add comment” … when clicked it shows comment form with submit button disabled
  • when user select text area for input comment -> loag google captcha
  • validate captcha and, if it is ok -> enable submit button in wp comment form

After various researches and tests I solved in this way…. thanks to various posts found on stackoverflow

  1. I uninstalled the plugin used to insert google recaptcha

  2. In the function.php, when i enqueue js script I added:

JavaScript
  1. In the style.css file I have inserted the following code:
JavaScript
  1. In my template I changed comments.php in this way:
     <button type="button" class="btn btn-primary ffita-add-comment">Add a comment</button>
     <div id="ffita-captcha"> </div> //div where google captcha will be displayed
JavaScript
  1. in file ffita_base_function.js (previously enqueue in function.php) I added this function. NOTE: I used developer key by google in this sample script. https://developers.google.com/recaptcha/docs/faq use own keys in production environment
JavaScript

NOTE: in ffita_form_activate function I have two different ways to test captcha response… based on simple_chk var. If simple_chk is true I check the length of the response received from grecaptcha.render…. if response lenght is not 0 I evaluate captcha solved

If simple_chk is false I pass the response value to php file (g_recaptcha_verify.php) for verification

  1. I create g_recaptcha_verify.php for server side verification of captcha NOTE: I used developer key by google in this sample script. https://developers.google.com/recaptcha/docs/faq use own keys in production environment
JavaScript
  1. FINISHED!! You can see a working example on any post on my site 🙂
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement