最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览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?

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 0
Add a comment  | 

2 Answers 2

Reset to default 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

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;
}
发布评论

评论列表(0)

  1. 暂无评论