# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: comments, spam, bots
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/comment-require-referer/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Block Comments Posted Without Visiting Your Site" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
