WordPress HTTP Domain Blocker: Stop Slow External API Calls
This WordPress code snippet dramatically improves site performance by blocking slow external HTTP requests that can bog down your website. Many WordPress plugins make API calls to external services like GitHub, social media feeds, or third-party widgets that can take 8-20 seconds to respond, causing your entire page to load slowly.
What This Snippet Does
The code uses WordPress's
pre_http_request
filter to intercept outgoing HTTP requests before they're sent. When a request is made to any domain in your blocked list, instead of waiting for the slow external server to respond, it immediately returns a fake "successful" response (HTTP 200 OK) with empty content. This prevents plugins from throwing errors while eliminating the performance bottleneck.Key Benefits
- Instant Performance Boost: Eliminates 8-20 second delays from slow external APIs
- Error Prevention: Returns proper HTTP 200 responses so plugins don't break
- Selective Blocking: Only blocks specific domains you choose, other requests work normally
- Easy Customization: Simply add or remove domains from the array
- Zero Plugin Dependencies: Pure WordPress code that works with any theme or plugin setup
Perfect For
- Sites using plugins that make slow GitHub API calls
- Websites with social media feed widgets that timeout
- E-commerce sites with slow payment gateway checks
- Any WordPress site suffering from external API performance issues
How It Works Technically
- Hooks into WordPress's HTTP request system using
pre_http_request
filter - Parses the destination URL of each outgoing request
- Checks if the domain matches your blocked list
- Returns a mock successful response for blocked domains
- Allows all other HTTP requests to proceed normally
This approach is much more effective than trying to disable individual plugin features, as it works at the WordPress core HTTP level regardless of which plugin is making the slow request.
Snippet
//https://raw.githubusercontent.com
// In your plugin's main file
add_filter('pre_http_request', 'block_domains_http_request', 10, 3);
function block_domains_http_request($preempt, $parsed_args, $url) {
// Domains to completely block
$blocked_domains = array(
'raw.githubusercontent.com',
'external-widget.com',
'social-feed.example.com',
);
$parsed_url = parse_url($url);
if (isset($parsed_url['host']) && in_array($parsed_url['host'], $blocked_domains)) {
// Return a fake successful response to prevent errors
return array(
'headers' => array(),
'body' => '',
'response' => array(
'code' => 200,
'message' => 'OK'
),
'cookies' => array(),
'filename' => null
);
}
return $preempt; // Let other requests proceed normally
}