Using the WordPress HTTP API to Block Unauthorized IPs in Your Plugin
A WordPress plugin can use the HTTP API to retrieve an IP deny list from a central service, security platform, or private endpoint, then reject matching visitors before they reach protected functionality. This approach is useful when several sites need the same rules or when a security team maintains addresses outside WordPress.
The HTTP API handles outbound requests through functions such as wp_safe_remote_get() and wp_remote_retrieve_body(). It does not directly block an incoming connection at the web server level. Your plugin must obtain trusted data, cache it, identify the visitor safely, and apply a suitable WordPress response without creating a new performance or availability problem.
Understand what the HTTP API can do
The request path has two separate parts. First, the plugin contacts an external endpoint and downloads a list of blocked IPv4 or IPv6 addresses. Secondly, WordPress compares the current request’s client address against that list. Keeping these responsibilities separate makes the code easier to test and lets you replace the data provider without rewriting the enforcement layer.
A remote list is valuable for distributed sites, managed WordPress installations, and WooCommerce stores that receive attacks from the same networks. An Australian retailer operating sites in Sydney, Melbourne, and Brisbane, for example, might use one centrally maintained list across regional storefronts. A local list stored in an option or custom table can still be useful for one-off bans, while an external list provides better coordination.
Do not call the remote service on every page request. Even a fast endpoint adds network latency, and a slow or unavailable provider could make an otherwise healthy site appear broken. Fetch the list on a schedule, store the result in a transient or custom table, and use the last valid copy during temporary failures. The plugin should generally fail open when the list cannot be refreshed, unless the protected application has a documented fail-closed requirement.
The source should return a strict format, such as JSON:
{
"blocked": [
"203.0.113.10",
"2001:db8::25"
],
"expires": "2026-12-31T00:00:00Z"
}
Treat the response as untrusted input. A successful HTTP status does not prove that the body is valid, complete, or safe to use.
Retrieve and validate the deny list
Use WordPress HTTP functions rather than PHP cURL directly. The WordPress API respects the site’s HTTP transport configuration and provides consistent error handling across hosting environments. A fixed provider URL is preferable to accepting an arbitrary URL from an administrator, because unrestricted outbound requests can introduce server-side request forgery risks.
The following example fetches a list with a short timeout, validates every address, and caches the accepted values for fifteen minutes:
function acme_get_blocked_ips() {
$cached = get_transient( 'acme_blocked_ips' );
if ( false !== $cached && is_array( $cached ) ) {
return $cached;
}
$response = wp_safe_remote_get(
'https://security.example.com/v1/blocked-ips',
array(
'timeout' => 3,
'headers' => array(
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . ACME_IP_FEED_TOKEN,
),
)
);
if ( is_wp_error( $response ) ) {
return array();
}
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
return array();
}
$payload = json_decode( wp_remote_retrieve_body( $response ), true );
if ( empty( $payload['blocked'] ) || ! is_array( $payload['blocked'] ) ) {
return array();
}
$blocked = array();
foreach ( $payload['blocked'] as $address ) {
if ( is_string( $address ) && filter_var( $address, FILTER_VALIDATE_IP ) ) {
$blocked[] = $address;
}
}
$blocked = array_values( array_unique( $blocked ) );
set_transient( 'acme_blocked_ips', $blocked, 15 * MINUTE_IN_SECONDS );
return $blocked;
}
Store credentials in wp-config.php, an environment variable, or the hosting platform’s secret manager instead of saving an API token in a public plugin setting. If the provider uses signed responses, verify the signature before accepting the address list. A checksum alone is not useful when it is delivered through the same compromised channel as the data.
For larger lists, a PHP array lookup is quicker than repeatedly scanning with in_array(). Normalise the representation consistently, especially when IPv6 addresses may use different textual forms. If the provider returns CIDR ranges rather than individual addresses, use a reliable range-matching implementation and test it thoroughly; comparing a visitor’s IP with the literal network string will not block a subnet correctly.
Cache data and enforce the decision
The enforcement point should be as early as practical, but it should match what the plugin is protecting. A front-end page can be stopped during template_redirect, while a REST endpoint should use rest_pre_dispatch. An AJAX action can check the address inside its action callback. A plugin should avoid blocking all WordPress requests from a general-purpose hook unless that behaviour is explicitly part of its purpose.
A simple front-end check might look like this:
add_action( 'template_redirect', 'acme_reject_blocked_visitors', 1 );
function acme_reject_blocked_visitors() {
if ( is_admin() || wp_doing_cron() || wp_doing_ajax() ) {
return;
}
$client_ip = isset( $_SERVER['REMOTE_ADDR'] )
? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) )
: '';
if ( ! filter_var( $client_ip, FILTER_VALIDATE_IP ) ) {
return;
}
if ( in_array( $client_ip, acme_get_blocked_ips(), true ) ) {
status_header( 403 );
nocache_headers();
wp_die(
esc_html__( 'Access denied.', 'acme-plugin' ),
esc_html__( 'Forbidden', 'acme-plugin' ),
array( 'response' => 403 )
);
}
}
REMOTE_ADDR is normally the address of the immediate connection. On a reverse proxy, load balancer, or content delivery network, it may be the proxy rather than the visitor. Never trust HTTP_X_FORWARDED_FOR, HTTP_CLIENT_IP, or similar headers from arbitrary clients. Only use forwarded headers after configuring a known list of trusted proxy addresses and parsing the header according to that infrastructure’s documented rules.
The cache strategy determines how quickly a ban takes effect and how resilient the site is when the provider has an outage. The following choices suit different plugin requirements:
| Strategy | Suitable use | Main benefit | Main risk |
|---|---|---|---|
| Short transient | Small sites and ordinary threat feeds | Simple implementation | More frequent outbound requests |
| Scheduled refresh | Busy sites and WooCommerce stores | Predictable network traffic | A stale list may remain briefly |
| Custom database table | Large lists or audit-heavy systems | Efficient queries and history | More schema and maintenance code |
| Object cache | Sites with Redis or Memcached | Fast repeated lookups | Depends on cache availability |
| Web server or CDN rule | High-volume attacks | Blocks before PHP runs | Requires infrastructure access |
For a production plugin, schedule a single refresh with wp_cron rather than allowing the first visitor after expiry to perform the request. wp_cron is traffic-dependent, so Australian sites with quiet overnight periods may need a real server cron job or a hosting scheduler. The refresh task can retain the previous valid list if the provider returns an error and record the failure for administrators.
Connect the check to WordPress features
A plugin that protects a REST route should reject the request before expensive controller logic runs. The rest_pre_dispatch filter can return a WP_Error with a 403 status:
add_filter( 'rest_pre_dispatch', 'acme_protect_api_route', 10, 3 );
function acme_protect_api_route( $result, $server, $request ) {
if ( 0 !== strpos( $request->get_route(), '/acme/v1/' ) ) {
return $result;
}
$client_ip = isset( $_SERVER['REMOTE_ADDR'] )
? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) )
: '';
if ( in_array( $client_ip, acme_get_blocked_ips(), true ) ) {
return new WP_Error(
'acme_ip_blocked',
__( 'This address is not permitted.', 'acme-plugin' ),
array( 'status' => 403 )
);
}
return $result;
}
For login protection, avoid relying solely on a broad init hook. A block on every request can interfere with password resets, health checks, cron tasks, webhooks, and emergency administration. Provide an allowlist for trusted operational addresses, but do not assume an Australian office has a permanent IP address: staff working from home, mobile networks, and changing NBN connections can make an address-based allowlist fragile.
A WooCommerce plugin may need to distinguish between customer traffic and payment provider callbacks. Blocking a payment gateway’s changing addresses can leave orders stuck in pending status. Prefer the gateway’s signature verification, webhook authentication, and official IP guidance before adding its addresses to an allowlist. If a security decision applies only to account access, enforce it on login or account endpoints rather than on the entire shop.
Use proper response codes and headers. A 403 response communicates that the server understood the request but refuses it. nocache_headers() helps prevent a reverse proxy from serving the denial to a different visitor. Avoid displaying the blocked address, feed details, or internal rule identifier in the public message, since those details help attackers refine their attempts.
Handle privacy, logging, and failures
An IP address can be personal information under privacy laws, and an Australian business should consider the Privacy Act 1988 and the Australian Privacy Principles when collecting, sending, or retaining it. The compliance position depends on the business and processing context, but a sensible plugin design minimises retention. Store only what is needed for the security purpose, restrict administrator access, and document whether addresses are transmitted to a third-party provider.
Logs should be useful without becoming an attacker-controlled storage sink. Record a timestamp, event type, route category, and perhaps a privacy-conscious hash of the address. Limit repeated entries from the same source, rotate log files, and avoid writing complete request headers. If an external provider supplies the deny list, record refresh status, response code, and item count rather than copying its entire response into the WordPress debug log.
A stale feed is usually safer than an empty feed when the last successful list is still trustworthy. Keep separate metadata for the last successful refresh and the list itself, so the plugin can expose a warning when the data is older than the configured maximum age. Administrators should be able to see whether a block came from the remote list, a local rule, or a CIDR range.
Avoid making a remote call from inside the block decision. If the provider is down, the request should still complete using cached data. For sites hosted in Perth or Darwin, an overseas provider may introduce noticeably different latency from one hosted near Sydney, so a regional endpoint or a scheduled pull can make operational behaviour more consistent. The same principle matters for Australian stores during seasonal sales, when every additional PHP wait affects checkout performance.
Test and operate the blocking feature
Test valid IPv4 and IPv6 addresses, malformed data, duplicate entries, empty lists, expired transients, provider timeouts, HTTP 500 responses, invalid JSON, and oversized payloads. Use WordPress’s HTTP mocking tools in automated tests so the plugin does not contact a live security service. Verify that a failed refresh preserves the last valid list and that a newly fetched list replaces it only after validation.
Test each execution context separately: normal pages, logged-in administrators, REST requests, AJAX calls, WP-Cron, XML-RPC if enabled, and payment webhooks. Confirm that a blocked visitor receives a 403 response and that legitimate traffic gets the original response. If a site uses Cloudflare, a managed host, or a load balancer, test the actual proxy chain rather than assuming REMOTE_ADDR represents the end user.
A staging site should include proxy configuration that resembles production. For request inspection and callback testing, an HTTP monitoring service can help confirm what leaves WordPress and whether a test endpoint receives the expected method, headers, and payload. Keep production credentials and real customer addresses out of these tests.
Finally, document the refresh interval, provider ownership, trusted proxies, allowlist process, and emergency bypass. A concise administrator notice can explain how to clear the transient after changing a rule and where to find refresh errors. IP blocking is one layer of defence; capability checks, nonces, authenticated webhooks, rate limiting, secure server configuration, and regular WordPress updates should continue to protect the application when an address-based rule is bypassed or becomes stale.