How To Get Error Message When Using WordPress HTTP API

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?

How To Get Error Message When Using WordPress HTTP API

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
}

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

PS: we'll drop lifetime pricing from Dec 01, 2024. Get it now before it's gone!

Leave a Reply

Your email address will not be published. Required fields are marked *


Copyright © 2024 Deluxe Blog Tips. All rights reserved.

My products: Meta Box | Slim SEO