I am using Travelify theme and I am having some trouble restricting the characters in the comment section (textarea) or where the name or mail goes into the input tags.

I read some articles about changing the core files from wp-includes like post.php / post-formats.php / formatting.php , for changing the preg_match function and only allow a-zA-Z0-9 and some other like .,? characters or others to be used.And i would also like to add a text that appears that dosen't allow special characters.

I know that is not the best practice to change the core files, but some times it can help you.

  • 1
    Changing core files will always come back to haunt you. If you're concerned about sanitizing user input, read up on Data Sanitization in WordPress. – Caspar Apr 15 '16 at 0:31

Never edit the WordPress core files.

Instead you should hook into the pre_comment_content, which is where the comment text from the textarea is being sanitized, before it's inserted into the database.

In the example below preg_replace is used to sanitize the comment text submitted. You should modify the function to fit your needs.

function keha_filter_comment( $comment_content ) {
    $comment_sanitized = preg_replace( "/[^0-9a-zA-Z ]/", "", $comment_content );
    return $comment_sanitzed;
add_action( 'pre_comment_content', 'keha_filter_comment' );

There are also some other filter hooks available for the other comment fields available, you can find them within the WordPress code, look for the apply_filters, also listed below:

  • pre_comment_author_name
  • pre_comment_user_ip
  • pre_comment_author_url
  • pre_comment_author_email
  • pre_comment_content
  • Hi, sorry for the late response, I added the code into functions.php from themes folder.Alltough it lets me send the comment with special characters like !_^ and when i try to send it a second time it replies Duplicate comment detected; it looks as though you’ve already said that! . I mention the fact that the first comment in the admin dashboard has no content.... – Philipos D. Apr 17 '16 at 10:05
  • You need to alter the regular expression, not my strongest skill, but I think somebody out there should know how to modify it for you. Yes, you can not add the same comment twice. It's made this way by design, to avoid spam comments. – keha76 Apr 18 '16 at 9:58
  • I found a JQuery plugin that does the work jquery.alphanum , it's pretty good and works for paste (ctrl + v) too. – Philipos D. Apr 18 '16 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.