Publish2 JSON Feed Without A Plugin

Need: A way to display the JSON data provided by Publish2 on a WordPress blog.

The Catch: I wanted to have multiple instances of the feed from different JSON data feeds on the post. Furthermore, each required unique items from its respective JSON feed and I wanted to style each instance differently.

What’s Available: Publish2 has a great plugin out which would allow me to display the JSON feed via WordPress widget or directly in the template. However, I wanted something that was a little easier to control without the added bulk of a plugin.

Start by adding the following function to your theme’s functions.php file:

1
2
3
4
5
6
7
8
9
10
function wd_json_feed($url = 'LINK TO JSON FEED HERE', $size = 5) {
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$feed = curl_exec ($ch);
$feedArrAll = json_decode($feed, true);
$feedArr = array_slice($feedArrAll['items'], 0, $size);
return $feedArr;
}

Next, add the following code wherever you’d like to parse the Publish2 data feed (replace with a link to your JSON data feed and set the number of items to display):

1
2
3
4
5
6
7
8
9
10
<?
$feed = wd_json_feed('LINK TO JSON FEED HERE', 3);
foreach ($feed as $item) {
?>
<?=$item['link']?>
<?=$item['title']?>
<?=$item['publication_name']?>
<?
}
?>

In the example above, I am displaying 3 items and getting the Link URL, Title, and Publication Name for each.

Enjoy!

Tags: ,

Leave a Reply