creating shortcode to pull json array

Frankly – this may be a duplicate of another question I have out there. Sorry if it is. I’m learning this site and PHP/Wordpress development. I have partnerships with local sites that use JSON and we’re working together. They aren’t WordPress specialists though.

I want to pull what my friend calls a JSON object from this url:

http://aggrenda.com/mpellas/michael-pellas/events.json

I’m trying to create a shortcode that can parse the data into scheduled posts. I have specific date, address, description (and other) data.

I’ve been working with my PHP at phpfiddle.org and have been successful. I haven’t been able to translate anything to WordPress functionality though.

Here’s one of my latest attempts:

add_shortcode('aggrenda', 'requestAggrendaEvents');
function requestAggrendaEvents() 
{
$json = file_get_contents("http://aggrenda.com/mpellas/michael-pellas/events.json");
$data = json_decode($json, true);
var_dump($data['events'][1]['title']);
}

The basic php works, but if I chnge file_get_contents with wp_remote_get I end up with nothing but a blank page…or a null return depending on little variations in my code. I put everything into functions.php.

I have anumber of other snippets where the PHP works but i can’t translate it to WP functionality. I’m sure i’m mssing something small. Help?

1 Answer
1

As per documentation on wp_remote_get() it doesn’t return you just the body of requested resource. Its return will be either the array of data or WP_Error object on failure.

The simplest snippet to get to the body would be:

$json = wp_remote_retrieve_body( wp_remote_get( $url ) );

PS it’s kinda weird to be doing this in shortocde, are you sure it’s most appropriate place for it? 🙂

Leave a Comment