Building a Feed from WordPress’s REST API

For reasons not worth elaborating on, I was tasked with building a feed based on WordPress’s REST API (as opposed to pulling in an RSS feed). This was a new experience for me.

The default URL to grab posts is /wp-json/wp/v2/posts, so for example https://smithtalkstech.com/wp-json/wp/v2/posts

That is sufficient if you just want the text of the posts you want to pull in, but you probably want some kind of images too, right? Perhaps whatever you’re using for a thumbnail. I don’t actually use featured images here so this blog is a terrible example, but suffice to say that /wp-json/wp/v2/posts will pull in links to the attachment page, but not the actual image URLs.

So you’ll find something like wp:featuredmedia blah blah href: mysite.com/wp-json/wp/v2/media/8794

You could then do another call to that URL and get all the data, including the URL to the image, but there’s a slightly easier way: append ?_embed to the end of your URL: https://smithtalkstech.com/wp-json/wp/v2/posts?_embed

Now you’ll have an _embedded node in your JSON that holds what you need, but gotta dig down a few levels
_embedded -> wp:featuredmedia -> 0 -> media_details -> sizes -> thumbnail {for example} -> source_url

If you’re like me, some of those special characters will throw you off. Here is a working example:

$mediaUrl = $obj->_embedded->{'wp:featuredmedia'}[0]->media_details->sizes->{'post-thumbnail'}->source_url;

$mediaURL now holds the URL to your thumbnail image.

$obj is the json object. In this case I was grabbing a custom image size called post-thumbnail

Putting wp:featuredmedia inside quotes inside curly braces was new to me.

Everything else is pretty easy. $obj->link for the URL of the post, $obj->title->rendered for the post title, $obj->content->rendered for the post content, and so on.

I highly suggest using Firefox to look at these json files since it formats stuff for you. Or snag a json viewer extension for your favorite browser.

By the way, by default you’ll get 1 page of 9 posts. You can control how many posts you get by appending a per_page value.

So say I wanted the most recent 3 posts (and I want the embed stuff): https://smithtalkstech.com/wp-json/wp/v2/posts?_embed&per_page=3

Here’s the full documentation for /posts: https://developer.wordpress.org/rest-api/reference/posts/