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?
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?
Share Improve this question edited Jun 26, 2019 at 4:25 Bryan asked Jun 26, 2019 at 3:09 BryanBryan 411 silver badge7 bronze badges 02 Answers
Reset to default 3Your 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
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;
}