One problem I've met when using WordPress HTTP API is that I couldn't show the error message to users when the connection has failed. There are various problems of connection failure such as wrong URL, timeout, server block, etc. Users (and developers) need to see the error message to fix the PHP code or ask for support. But looking through the HTTP API Documentation, we see that there's no entries for error message. All you can do (with the functions at the Codex) is getting the error code via wp_remote_retrieve_response_code()
. You might say: that's OK, I know the response code then I know the error message by looping an array of error codes. But what happens if you need to send many requests? Do you need to repeat the code of checking error code each time?
Instead of that, WordPress provides us a better way to receive error message (not documented yet). When a request has failed, it presents itself an instance of WP_Error
class. The WP_Error
class has a method get_error_message()
that receives the error message. So, the code to get error message will look like this:
$request = wp_remote_post( $url ); if ( is_wp_error( $request ) ) { // If the request has failed, show the error message echo $request->get_error_message(); } else { $content = wp_remote_retrieve_body( $request ); // Do stuff with $content }
Leave a Reply