Block IP Addresses and Ranges
Denies access to the whole site for the IP addresses and IPv4 ranges you list, for example a persistent spammer or attacker.
Opens WPIDE on
Code
// Single addresses (IPv4 or IPv6) or IPv4 ranges in CIDR form.
$wpide_blocked_ips = array( '192.0.2.10', '198.51.100.0/24' );
$wpide_visitor_ip = isset( $_SERVER['REMOTE_ADDR'] ) ? (string) $_SERVER['REMOTE_ADDR'] : '';
if ( $wpide_visitor_ip && ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
foreach ( $wpide_blocked_ips as $wpide_entry ) {
$wpide_match = false;
if ( false === strpos( $wpide_entry, '/' ) ) {
$wpide_match = ( $wpide_visitor_ip === $wpide_entry );
} elseif ( filter_var( $wpide_visitor_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
list( $wpide_subnet, $wpide_bits ) = explode( '/', $wpide_entry, 2 );
$wpide_mask = -1 << ( 32 - (int) $wpide_bits );
$wpide_match = ( ip2long( $wpide_visitor_ip ) & $wpide_mask ) === ( ip2long( $wpide_subnet ) & $wpide_mask );
}
if ( $wpide_match ) {
status_header( 403 );
header( 'Content-Type: text/plain; charset=utf-8' );
exit( 'Access denied.' );
}
}
}
Notes
Behind Cloudflare or another proxy, REMOTE_ADDR is the proxy; configure your server to pass the real visitor IP first.
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.