Created
March 19, 2014 08:48
-
-
Save thanh4890/9637858 to your computer and use it in GitHub Desktop.
Add an extra anti spam comment form field in WordPress comment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Extra anti spam comment form field | |
* | |
* @package ndt_framework | |
*/ | |
/** | |
* Add anti spam comment form field | |
* @param array $fields The default comment fields. | |
*/ | |
add_filter( 'comment_form_default_fields', 'ndt_add_anti_spam_comment_field' ); | |
function ndt_add_anti_spam_comment_field( $fields ) { | |
// get random values for anti spam question | |
$num1 = mt_rand(1, 10); | |
$num2 = mt_rand(1, 10); | |
// get operator by string | |
$operator = apply_filters( 'ndt_anti_spam_operator', '+' ); | |
$total = $num1 + $num2; | |
// validate operator | |
if ( '*' == $operator ) { | |
$total = $num1 * $num2; | |
} else { | |
$operator = '+'; | |
} | |
$random_string = ( (string) $num1 ) . ' ' . $operator . ' ' . ( (string) $num2 ) . ' = ?'; | |
$req = get_option( 'require_name_email' ); | |
$aria_req = ( $req ? " aria-required='true'" : '' ); | |
$fields['anti_spam'] = '<p class="comment-form-anti-spam">' . '<label for="anti-spam">' . __( 'Anti spam question', 'ndt_framework' ) . ( $req ? ' <span class="required">*</span>' : '' ) . '</label> ' . | |
'<input id="anti-spam" name="anti-spam" type="text" size="30"' . $aria_req . ' placeholder="' . $random_string . '" />' . | |
'<input type="hidden" name="rand-total" value="' . $total . '"></p>'; | |
return $fields; | |
} | |
/** | |
* Validate before posting comment | |
* @param int $comment_post_ID Post ID. | |
*/ | |
add_action( 'pre_comment_on_post', 'ndt_validate_anti_spam_question' ); | |
function ndt_validate_anti_spam_question( $comment_post_ID ) { | |
// get user answer | |
$answer = ( isset($_POST['anti-spam']) ) ? trim(strip_tags($_POST['anti-spam'])) : null; | |
// get correct answer | |
$correct_answer = ( isset($_POST['rand-total']) ) ? $_POST['rand-total'] : null; | |
$answer = (int) $answer; | |
$correct_answer = (int) $correct_answer; | |
// if user answer was wrong, exit immediately and print an error | |
if ( $answer !== $correct_answer ) { | |
wp_die( __('<strong>ERROR</strong>: your answer for anti spam question was wrong, please try again.'), 'ndt_framework' ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment