0

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?

0

2 Answers 2

3

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

1
  • Thanks. Maybe figured it out 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) && $response['response']['code'] != 200 ) { return false; } But now I get the error: Undefined index: response
    – Bryan
    Commented Jun 26, 2019 at 4:23
0

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 Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.