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

  • Terraform and segregated permissions
  • LVM Compression and Deduplication
  • Edit gpg encrypted file with vim
  • Lelit Elizabeth PL92T Pressure Tuning
  • jq transformation
  • aws (8)
  • coffee (1)
  • headfi (1)
  • linux (6)
  • others (58)
  • security (2)
  • tech (36)
  • wordpress (2)

apache aws awscli azure backup clearlinux cloud coffee docker DOCP ec2 EL8 epyc espresso featured gpg jenkins kernel lelit linux lvm meltdown memory MFA mikrotik php python rdp Redhat RHEL roasting rpm Ryzen site-to-site snapshot spectre tech terraform tuning ubuntu ubuntu upgrade vim vpn wordpress xdotool

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