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.