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:
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) : ?> <p class="no-comments"><?php _e( 'Comments are close.', 'ffita' ); ?></p> <?php endif; ?> <?php comment_form(); ?>
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:
comment_form();
then modify comment.php in this way
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) : ?> <p class="no-comments"><?php _e( 'Comments are close.', 'ffita' ); ?></p> <?php endif; ?> <div class="commenti"> <button type="button" id="ffita-add-comment" class="btn btn-primary">Add Comment</button> <script> $(document).ready(function(){ $("#ffita-add-comment").click(function(){ event.preventDefault(); $.ajax({ type: 'GET', url: '/wordpress/wp-content/themes/ffita/template-parts/comment_form.php', success: function(response){ $( '#ffita-comment-form' ).html( response ); }, }); }); }); </script> <div id="ffita-comment-form"> </div> <?php //comment_form(); ?>
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
I uninstalled the plugin used to insert google recaptcha
In the function.php, when i enqueue js script I added:
wp_enqueue_script( 'ffita_base_functions_js', get_template_directory_uri() . '/inc/js/ffita_base_functions.min.js', array ( 'jquery' )); //enqueue js script wp_localize_script('ffita_base_functions_js', 'ffita_var', array("ffita_theme_path"=> get_template_directory_uri()) ); //use wp_localize_sript to pass var data from PHP to JavaScript
- In the style.css file I have inserted the following code:
.comment-respond{ visibility: hidden; //default wordpress class for comment form } #ffita-captcha{ margin: 30px; }
- 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
<?php $comments_args = array( 'class_submit' => 'submit ffita-captcha-submit', //add a class to standar submit button ); comment_form($comments_args); ?> //wordpress function to call comments form <script> $(document).ready(function() { //jquery function var id_activation='comment'; //div id where click active captcha var id_captcha_view='ffita-captcha'; //div id where captcha will be displayed $('.ffita-captcha-submit').prop('disabled',true); //disable comment form submit button $('#'+id_activation).on('click', function(){ //when click on comment text area ffita_show_captcha(id_captcha_view); //call js function and pass id where display captcha }); $('.ffita-add-comment').on('click', function(){ //jquery for button...., when clicked $(this).hide(); //hide button $('.comment-respond').attr("style", "visibility: visible"); //show comment form }); }); </script>
- 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
function ffita_form_activate(resp){ //function call from the next var simple_chk=false; //false or true. see below notes if (simple_chk){ if (resp.length != 0 ) { //if response lenght is not 0 I evaluate captcha solved $('.ffita-captcha-submit').prop('disabled',false); //enable wp comment submit button } else { alert ("try again"); grecaptcha.reset(); //on failed reset captcha } } else { if (resp.length != 0 ) { local_path=ffita_var.ffita_theme_path; //var passed through wp_localize_script (theme root dir) $.ajax({ url: local_path+'/inc/g_recaptcha_verify.php', //php file for captcha verification see below type:'POST', data:{resp:resp}, success: function (response) { //php file returns OK if captcha was solved correctly if (response=="OK"){ $('.ffita-captcha-submit').prop('disabled',false); } else { alert ("try again") grecaptcha.reset(); } } }); } else { alert ("try again"); grecaptcha.reset(); } } } var captchaLoaded = false; function ffita_show_captcha(id_captcha_view){ //function call from jquery - comment.php // If we have loaded script once already, exit. if (captchaLoaded) { return; } // Variable Intialization var head = document.getElementsByTagName('head')[0]; var recaptchaScript = document.createElement('script'); //key for develop (site key) var recaptchaKey = '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'; //is key for developer...insert you public key!! // Dynamically add Recaptcha Script recaptchaScript.type = 'text/javascript'; recaptchaScript.src = 'https://www.google.com/recaptcha/api.js'; // Dynamically load script head.appendChild(recaptchaScript); //check grecaptcha is defined otherwise I wait var poll; var timeout = 200; poll = function () { setTimeout(function () { timeout--; if (typeof grecaptcha !== 'undefined') { grecaptcha.render(id_captcha_view, //where catpcha is shown { 'sitekey': recaptchaKey, 'theme': "light", 'callback': ffita_form_activate, //call for prev function, return response from google function } ); } else if (timeout > 0) { poll(); } else { alert ("Failed to load. Please retry"); } }, 200); }; poll(); //Set flag to only load once captchaLoaded = true; }
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
- 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
<?php //developer value //Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI //Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe // check post value: if (isset($_POST['resp'])) { // Create POST request: $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'; $recaptcha_secret = '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe'; //insert your secret key!! $recaptcha_response = $_POST['resp']; // Send POST request and decode respone: $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response); $recaptcha = json_decode($recaptcha); // Google response evaluation: if ($recaptcha && $recaptcha->success) { echo ("OK"); //used in jquery } else { // echo ("NO_OK"); //use in jquery } } ?>
- FINISHED!! You can see a working example on any post on my site 🙂