Skip to content

Instantly share code, notes, and snippets.

@chrmrtns
Created November 16, 2023 11:02
Show Gist options
  • Save chrmrtns/c579b79b09279d31e28044214f4a5b68 to your computer and use it in GitHub Desktop.
Save chrmrtns/c579b79b09279d31e28044214f4a5b68 to your computer and use it in GitHub Desktop.
Honeypot for Wordpress Comments - hide and use the url field for spam protection
/**
*
* @author Chris Martens
* @link https://chris-martens.com/
* @link https://chris-martens.com/blog/honeypot-fuer-kommentarfunktion/
* @snippet Comments without URL Field.
*
*/
/** Reduce spam comments */
function chrmrtns_remove_comment_author_link( $return, $author, $comment_ID ) {
return $author;
}
add_filter( 'get_comment_author_link', 'chrmrtns_remove_comment_author_link', 10, 3 );
function chrmrtns_remove_comment_author_url() {
return false;
}
add_filter( 'get_comment_author_url', 'chrmrtns_remove_comment_author_url');
/** Remove website field - uncomment filter if you want to use this */
function chrmrtns_remove_website_field($fields) {
unset($fields['url']);
return $fields;
}
//add_filter('comment_form_default_fields', 'chrmrtns_remove_website_field', 60);
/** Honeypot Check - instead of hiding this, you can send it to trash or spam */
function chrmrtns_hide_website_field($fields) {
// Hide the URL field using inline CSS
$fields['url'] = '<div style="display: none;">' . $fields['url'] . '</div>';
return $fields;
}
add_filter('comment_form_default_fields', 'chrmrtns_hide_website_field', 60);
function chrmrtns_check_comment_for_honeypot( $commentdata ) {
if ( !empty($_POST['url']) ) {
// Move the comment to trash instead of dying
add_filter('pre_comment_approved', 'chrmrtns_send_comment_to_trash');
}
return $commentdata;
}
/** Return either trash or spam */
function chrmrtns_send_comment_to_trash( $approved ) {
// 'trash' moves the comment to trash
// 'spam' moves the comment to spam
return 'trash';
}
add_filter( 'preprocess_comment', 'chrmrtns_check_comment_for_honeypot' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment