Friday, June 27, 2014

How to show the error messages in the same comment form in Wordpress.





 How to show the error messages in the same comment form in Wordpress .
Today i am discussing about how to show the error messages in the same wordpress comment form. Every one knows that as default wordpress comment form shows the error in a new page, from a user perspective it is very difficult to go to the next page, and then showing the error message and manually he comes back to the old page. So for avoiding that we found a solution for this behavior. That is pretty simple. We can achieve this by using some Jquery and some php codes.

Here I am showing how to show the duplicate error message in the same comment page and comment form validation.

Take your comments.php file, it is located in wordpress/wp-includes/comment.php

take a function called wp_allow_comment

Find this line die( __('Duplicate comment detected; it looks as though you’ve already said that!') );

replace this line with below codes

$url = add_query_arg( 'comment_error', 10, get_comment_link());
wp_redirect( $url );
exit;

Find this line
wp_die( __('Duplicate comment detected; it looks as though you’ve already said that!') );

replace this line with below codes
$url = add_query_arg( 'com_err', 10,get_comment_link());
wp_redirect( $url );
exit;

So it wont let you go to the error page.
After loading the comment form then we put below code. Then the error message will appear in the same page.

<script type="text/javascript">
jQuery("#submit").click(function () {
var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/;
jQuery("#errordisp").remove();
if(jQuery("#author").length)
{
if(jQuery("#author").val().trim()=='' ){
showMessage('author','Please enter your name.');
jQuery("#author").focus();
return false;
}
if(jQuery("#email").val().trim()=='' ){
showMessage('email','Please enter your email address.');
jQuery("#email").focus();
return false;
}
if(!jQuery("#email").val().match(emailRegex)){
showMessage('email','Please enter a valid email address.');
jQuery("#email").focus();
return false;
}
if(jQuery("#url").val().trim()!='' ){
if(!jQuery("#url").val().match(urlPattern))
{
showMessage('url','Please enter a valid web Url.');
jQuery("#url").focus();
return false;
}
}
}
if(jQuery("#comment").val().trim()=='' ){
showMessage('comment','Please enter comment.');
jQuery("#comment").focus();
return false;
}
return true;
});
function showMessage(target,mes)
{
jQuery( 'html, body' ).animate({scrollTop:jQuery('#respond').position().top}, 'slow');
jQuery('<div id="errordisp">'+ mes + '</div>').insertAfter('#'+target);
setTimeout(function() { jQuery('#errordisp').remove(); }, 5000);
}
jQuery("#cancel-comment-reply-link").click(function(){
jQuery("#comment").val('');
jQuery("#errordisp").hide();
});
</script>