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.

facebookShare on Facebook
TwitterTweet

Leave a Reply Cancel reply

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

Full text search

Recent Posts

  • Dumping AWS Organization tree
  • Free is the most expensive
  • Terraform conditional resource and blocks
  • Upgrade Ubuntu 16.04 to latest release
  • Inspect and control network traffic on AWS
  • aws (8)
  • coffee (1)
  • headfi (1)
  • linux (7)
  • others (55)
  • security (2)
  • tech (36)
  • wordpress (2)

apache aws awscli azure backup cloud coffee coreos distributed filesystem docker ec2 EL8 elasticcache etckeeper featured heartbleed kernel linux mail meltdown mysql php pine python rdp rds Redhat Red Hat RHEL RHEL7 rpm Ryzen snapshot spectre SSL systemd tech terraform ubuntu ubuntu upgrade vector vpn wordpress xtreemfs yum

©2022 blog.headdesk.me | Powered by SuperbThemes & WordPress