Menu
blog.headdesk.me
blog.headdesk.me

Writing a wordpress plugin to filter comments

Posted on 2017/08/262017/08/28

I’m completely new to wordpress plugin development. I want to write a plugin to delete comments I don’t want based on a keyword list.

Update: WordPress already comes with this feature under Comment Moderation

The code

The code isn’t complex. It first use the preprocess_comment hook to check the comment content. If it contains hyperlinks, a 404 error will be returned and the comment will not be inserted into database.

 
/*
 Plugin Name: Keyword Based Spam Removal
 Plugin URI: http://wp-plugins.headdesk.me
 Description: a plugin to delete spam based on a defined keyword list
 Version: 0.2
 Author: xpk
 Author URI: http://blog.headdesk.me
 License: GPL2
*/

add_filter( 'preprocess_comment', 'examine_comment', '' , 1 );
function examine_comment($commentdata) { 
  if (preg_match('/https?:/i', $commentdata['comment_content'])) { 
    $commentdata['comment_content'] = "Comment contains hyperlink and sanitized."; 
    $commentdata['comment_post_ID'] = 64277; 
    error_log("WPPL-SPAM: Link detected, content removed");     
    wp_die( __( 'ERROR: Bad comments are disabled.' ), '', array( 'response' => 404 ) ); 
  } 
  return ($commentdata);
}

add_action( 'rest_insert_comment', 'drop_rest_comment');
function drop_rest_comment() {
 wp_die( __( 'ERROR: REST comments are disabled.' ), '', array( 'response' => 404 ) );
}

// The following is no longer needed
add_action('comment_post', 'delete_comment',10,3);
function delete_comment($id, $approval, $commentdata) {
	if ($commentdata['comment_post_ID'] == 64277)
		wp_delete_comment($id, $force_delete = true);
}

Thanks to 146.185.223.125 who kept spamming my site and helped improved my code.

Loading

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Full text search

Recent Posts

  • Generate secure password
  • AWS Compute Savings Plans
  • AWS Zonal Shift
  • Coffee break…
  • Prevent private key from being committed to git
  • aws (14)
  • coffee (2)
  • headfi (1)
  • linux (9)
  • others (61)
  • security (2)
  • tech (41)
  • terraform (3)
  • wordpress (2)

Loading

apache aws awscli azure backup boot cloud coffee docker ec2 EL8 ElasticBeanstalk espresso featured git kernel lelit linux lvm meltdown MFA nat gateway php power proliant python rdp Redhat RHEL rpm Ryzen scp security smartarray smart switch snapshot spectre tech terraform ubuntu ubuntu upgrade vpn windows wordpress workspace

©2026 blog.headdesk.me | Powered by SuperbThemes