Block external requests for faster local development

I always develop sites locally. My local environment is using Docker, which I will probably cover in an upcoming blog post series. Sometimes I’m experiencing really long request times, especially in the WordPress backend. As I also usually use the Query Monitor plugin while developing, I quickly found out that some HTTP requests were failing. Those have been triggered either by core or some premium plugins/theme, usually to check for updates.

Blocking external requests

In order to fix those requests, I’ve deactivated them by removing the filters or actions that triggered those requests. Then I found an easier way by a global filter:

add_filter( 'pre_http_request', '__return_true', 100 );

But this was not the easiest or best way, as this will block all requests, no which host they are using. To block only external requests, we can simply set a constant:

define( 'WP_HTTP_BLOCK_EXTERNAL', true );

This will not block any local request, which might be need for cron jobs or other functionalities.

Allowing some external hosts

Sometime you cannot simply block all external requests, as some plugins/theme you develop user external APIs. For those hosts, you can set another constant with a comma separated list of those hosts:

define( 'WP_ACCESSIBLE_HOSTS', 'example.com, *.example.com' );

As you can see in my example, you can also use a wildcard for subdomains. This will be parsed and replaced with a regex pattern allowing any depth of subdomains for the given domain.

Blocking more then just HTTP requests

The two constant can really help to block any external HTTP requests triggered by WordPress. This although only work, when the WordPress API functions for HTTP requests are used. If a plugin/theme is using file_get_contents, curl or similar functions directly, it does not block those requests.

It will also not block any request made by the browser. If you want to block those requests as well, you can try out the plugin “Offline Mode” written by Frank Bültge you can download and install from GitHub. This will try to block as many external requests as possible.

Conclusion

Working locally is always the best thing to do, when working on a project. But if you don’t have a stable internet connection (or non, like on a plane), it can slow down your local development environment dramatically. Using these constants can bring back the speed your are used to.

Posted by

Bernhard is a full time web developer who likes to write WordPress plugins in his free time and is an active member of the WP Meetups in Berlin and Potsdam.

Leave a Reply

Required fields are marked *.