Block Comments Posted Without Visiting Your Site
Rejects comment submissions that do not come from a page on your own site, which stops bots that post directly to wp-comments-post.php.
Opens WPIDE on
Code
add_filter( 'preprocess_comment', function ( $commentdata ) {
if ( is_user_logged_in() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || wp_doing_ajax() || ( isset( $commentdata['comment_type'] ) && in_array( $commentdata['comment_type'], array( 'pingback', 'trackback' ), true ) ) ) {
return $commentdata;
}
$referer = isset( $_SERVER['HTTP_REFERER'] ) ? (string) wp_parse_url( esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ), PHP_URL_HOST ) : '';
$origin = isset( $_SERVER['HTTP_ORIGIN'] ) ? (string) wp_parse_url( esc_url_raw( wp_unslash( $_SERVER['HTTP_ORIGIN'] ) ), PHP_URL_HOST ) : '';
$host = (string) wp_parse_url( home_url(), PHP_URL_HOST );
if ( $host !== $referer && $host !== $origin ) {
wp_die( 'Please post your comment from the article page.', 'Comment rejected', array( 'response' => 403, 'back_link' => true ) );
}
return $commentdata;
} );
Notes
Browsers send the page address when a form is submitted; very strict privacy setups that strip it entirely would be blocked, so watch for complaints.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.