Debugging WordPress HTTP API Remote Requests

If you’re writing WordPress code that makes remote requests and need to easily debug the requests, here’s some helper code to do it. This requires that you’re using WordPress’s HTTP API which you should already be doing — directly using cURL or other methods is wrong and a great way to make your code not cross-server compatible.

add_action( 'http_api_debug', 'viper_http_api_debug', 10, 5 );

function viper_http_api_debug( $response, $type, $class, $args, $url ) {
	// You can change this from error_log() to var_dump() but it can break AJAX requests
	error_log( 'Request URL: ' . var_export( $url, true ) );
	error_log( 'Request Args: ' . var_export( $args, true ) );
	error_log( 'Request Response : ' . var_export( $response, true ) );
}

That will log the request URL, the request arguments, and the whole response HTTP_API object to your error log file. The last message one will be pretty long/spammy but it’ll give you headers, the body, and everything else. Since it’s an instance of HTTP_API, you can also do things like this if you want to:

error_log( 'Response Code: ' . wp_remote_retrieve_response_code( $response ) );

One thought on “Debugging WordPress HTTP API Remote Requests

Comments are closed.