WP_Http response throws "Cannot use object of type WP_Error as array"

My plugin is throwing the error "Cannot use object of type WP_Error as array". The line in question is...

$http = new WP_Http();
$response = $http-request( $url, array('timeout' = 20));

if( $response['response']['code'] != 200 ) { // THIS IS THE LINE
    return false;
}

$upload = wp_upload_bits( basename($url), null, $response['body'] );

So the problem is $response only has one result, so it's not an array? How do I fix this?

Topic wp-error http-api plugins Wordpress

Category Web


OK, I think may have fixed it by doing this...

$http = new WP_Http();
$response = $http->request( $url, array('timeout' => 20));

$response = is_array($response) ? $response : array($response);

if( is_wp_error($response) && isset($response) && $response['response']['code'] != 200 ) {
    return false;
}

Your logic for your updated if statement is wrong.

if( !is_wp_error($response) && $response['response']['code'] != 200 )

Here you are saying; if NOT wp_error AND response code NOT 200 return false. So your not actually catching the WP_Error

I believe what you are after is something like:

if ( is_wp_error($response) || $response['response']['code'] != 200 ) return false;

IS wp_error OR code NOT 200

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.