Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress How to Build a WordPress Plugin Connecting WordPress Plugins with 3rd Party APIs Getting and Storing JSON Code Challenge

suyash patankar
suyash patankar
2,310 Points

Fatal error: Cannot use object of type WP_Error as array

I am getting error "Fatal error: Cannot use object of type WP_Error as array in D:\xampp\htdocs\wordpress\wp-content\plugins\wptreehouse-badges\wptreehouse-badges.php on line 92"

the code is as follows

function wptreehouse_badges_get_profile($wptreehouse_username) { $json_feed_url= 'http://teamtreehouse.com' . $wptreehouse_username .'json'; $args = array('timeout'=> 120);

      $json_feed = wp_remote_get($json_feed_url, $args);

      $wptreehouse_profile = json_decode($json_feed['body']); //THIS IS LINE 92

      return $wptreehouse_profile; //to reutrn body data and not the array data in json file.


1 Answer

Luke Towers
Luke Towers
15,328 Points

You are attempting to access the body array element of the $json_feed variable. However, when this code is being run, $json_feed is not an array, it is an object of type WP_Error. Thus, the error message saying that it can't use an object with a type of WP_Error as an array, which indicates to you that $json_feed is not what you expected it to be.

In this case, we can assume that given the $json_feed_url and $args provided, wp_remote_get() returned an object (class) of type WP_Error. I would look into why wp_remote_get() returned a WP_Error instance and not an array as you were expecting; perhaps debug the values of $json_feed_url and $args that were provided to wp_remote_get() when it was called.

Additionally, you should have some form of a sanity check in your code, because if you look at the documentation for wp_remote_get(), it states that it returns either an array or an instance of WP_Error. You could add a really lazy check in the form of verifying that the $json_feed variable is an array and that it has a body element specified as shown below.

// Attempt to get the JSON feed
$json_feed = wp_remote_get($json_feed_url, $args);

// Verify that the JSON feed returned something useful
if (is_array($json_feed) && !empty($json_feed['body'])) {
   $wptreehouse_profile = json_decode($json_feed['body']);
   return $wptreehouse_profile;
} else {
   return false; // wp_remote_get failed somehow