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

  • Error 0xc1900101 when updating to Windows 11 22H2
  • Apply changes to all member accounts in an AWS organization
  • RPI4 under voltage
  • Upgrade RockyLinux 8 to 9
  • Terraform and segregated permissions
  • aws (9)
  • coffee (1)
  • headfi (1)
  • linux (8)
  • others (57)
  • security (2)
  • tech (39)
  • wordpress (2)

Loading

apache apigateway aws awscli azure backup cloud coffee docker ec2 EL8 ElasticBeanstalk enpass espresso featured kernel lelit linux lvm meltdown MFA mikrotik nat gateway nginx php power python rdp Redhat RHEL rpm Ryzen s2s scp serverless site-to-site snapshot spectre tech terraform ubuntu ubuntu upgrade vpn wordpress xdotool

©2023 blog.headdesk.me | Powered by SuperbThemes