Using the WP-API to Fetch Posts

It may be news to you, but there is a nifty resource called Quotes on Design that serves up interesting quotes about design, curated by our very own Chris Coyier.

Up to this point, Quotes on Design (QoD) used a bit of custom code to query the WordPress database and serve up quotes. This was used for the site itself, and for its API to allow use on external sites. With the excitement surrounding the upcoming WordPress JSON REST API, we thought it would be fun to rebuild the site to use the WP API instead of our own custom code.

Here's what we'll cover:

Setting up the API

Querying the API to grab a random quote

Doing something interesting with that quote

Customizing the API to remove unused information

Using the new QoD JSON REST API to grab nifty quotes for your site

Warning! The WP JSON REST API is still in development, and the query interface could change before the final version. We'll do our best to update this tutorial if anything changes. We wouldn't recommend using the WP API on any super-important sites just yet, unless you're a ultra-professional WordPress developer, in which case you probably can skip this article, right?

Grabbing a random post

For QoD, we wanted to add some simple functionality to the home page: Click a button, and have a random quote reloaded from the API.

The WP API includes several endpoints you can use to read information from the database, including meta, attachments, users - really, anything that is stored in the standard WP database is accessible to some degree.

For our use case, we just needed to grab a random post. We started with the /wp-json/posts endpoint, which is essentially like running a WP_Query, if you're familiar with WordPress development. Here's the base endpoint URL:

http://quotesondesign.com/wp-json/posts

Visiting that URL without any query parameters returns the default list of posts in JSON format — essentially, the same list of posts you'd see on the blog page:

[
{
"ID": 2328,
"content": "<p>Everything we do communicates.</p>\n",
/* ...snip most of the fields... */
"title": "Pete Episcopo",
"type": "post"
},
{
"ID": 2326,
"content": "<p>The only &#8220;intuitive&#8221; interface is the nipple. After that it&#8217;s all learned.</p>\n",
/* ...snip most of the fields... */
"title": "Bruce Ediger",
"type": "post"
},
{
"ID": 2323,
"content": "<p>Only show work you like, or you&#8217;ll end up being hired to do things you don&#8217;t like.</p>\n",
/* ...snip most of the fields... */
"title": "Victoria Pater",
"type": "post"
}
]

Note that the IDs of the quotes are sequential: they represent the three most recent quotes on the site.

For our design, we only need one post and we want it to be randomly selected. We need to filter the results, and we can do this using the same arguments we would use when calling WP_Query or get_posts.

In this case, we need two arguments:

The orderby argument needs to be rand, to fetch a random post

The posts_per_page argument needs to be 1, to limit the results to a single post

Every time we refresh our filtered URL, we'll get a different quote. Sweet!

You'll notice that I've included more of the WP API JSON response in the last snippet. There's a lot of information there — even when I hide the meta, author and terms.

For our purposes, we don't need most of that information. Plus it's more bandwidth-effient to not include it all - so let's chop it out!

Removing fields from the JSON response

We need to filter the data being returned by the API, and fortunately the WP API provides us with exactly the filter we need, called json_prepare_post. To use it, we create a new plugin with the following snippet of code:

Adding fields to the JSON response

Now that we're done removing unnecessary information from the JSON data, it's only fitting that we add some of our own custom fields to stay balanced. Wax on, wax off.

Some of the quotes have a custom meta field called "Source", which Chris uses to link to the original source of the quote, if it is available online. Let's add that meta data to the JSON response using the same json_prepare_post filter we used to remove data previously. In the same plugin, we add the following function:

Now, when the button is pressed a new random quote is automagically loaded. Try it out.

Using the API on your site

You can query Quotes on Design using the API to show nifty quotes for your own site. We've updated the API page to use the new WP JSON API. As mentioned earlier, the WP API is subject to change, so don't rely on this API for uber-important sites just yet.

More API goodness is coming

Development on the WP API is ongoing, and there is a lot of excitement to see what folks can build with it. Our example is pretty basic, but the thought of a JSON API has already gotten our gears turning about the possibilities.

Check out Quotes on Design and share your thoughts and questions in the comments. And if you have a great quote you'd like to see on the site, submit it!

Related

Comments

Hey Andy, thanks for sharing this! It’s nice to see an example of the API in the wild.

Fwiw, from a practical standpoint, the API is actually at version 1.2.x for the stable version, and the version that should get proposed for core inclusion will be version 2.x, and 2.0 is in beta right now. The article notes it’s not yet at 1.0, which isn’t accurate.

There are lots of awesome potential use cases for the API and I’m excited to see this as another way folks are using it. I’m using it on my own site for an ad delivery system, actually. I think we’ll see all sorts of exciting use cases in the future.

Without wishing to be disparaging – instead of the regular WordPress articles of late – if there’s going to be non-CSS-related code here in that sphere, I’d really like it to be related to static site generators. I’d really love it if more web designers/developers were familiar with them so that we can maybe get a few more people away from WordPress and that ilk, and shut down the repeated crops of botnets that result from their security vulnerabilities (and the even more frequent vulnerabilities in their poorly written plugins).

I have a question about his method.
Each time you click the button on the website, an http request is made to the WP API. Am I right ?

I am planning on using WordPress as an API for my website(s) but I can’t imagine doing that. Because let’s say the Quotes on Design website becomes very popular. So popular that, say, 4000+ people click on the button at the same time, and repeatedly. The API calls would probably crash the server where WordPress is installed on.

What would be good solution to “cache” thoses API calls ? Should we imagein to make a CRON job that would automaticaly fetch all (and then only new quotes) – and put them on a local database or file storage ?) and make the random choice of quote directly on QoD’s server ?

Is there any system already existing that can help me manage API calls like this ?

Yes, you would probably want to cache each unique URL, and invalidate the cache whenever posts related to that URL are updated. I don’t know if existing caching plugins handle API URLs out of the box, but I’d expect them to handle API URLs once the API gets more traction.

I just wanted to add that when I wrote my thoughts on an API-first WordPress here on CSS-Tricks, I mentioned a couple of features that I couldn’t find on the WP-API which led me to work on my custom solution, and the main one being the ability to request multiple batches of content with a single request.

For those interested in using the WP-API while still having that feature, I’ve created a plugin that extends the WP-API implementing that functionality. It’s available on GitHub.

This is very helpful, would it be possible to shed some light on how you achieved the pretty URLs as well on each click? as I couldn’t see the method through the code.

What is interesting there is I thought this method would not be so great for SEO as the pages might not get indexed, but it seems that I was wrong, ran a quick “site:http://quotesondesign.com/” search on google and all the quote seems to be indexed which is great news.

Correcting myself… The behavior is actually a little bit weird. If I load a quote and click the tweet link, it doesn’t show the full excerpt. However if I reload the page and click the tweet link again, it populates the tweet correctly. The tweet also works properly if I refresh the page once before ever clicking.

Are you sure your code is being executed? Try putting var_dump( $data ); exit; in the place you’re trying to unset and visit the page. Did the code get there? If not, where is it stopping? If so, what is the state of the $data variable? That’s where I’d start.

Sorry so I am trying to unset specific values for a curl. I did a var dump and all of the content passes through. I am using this line. curl -i localhost/wp-json/posts?type=custom_post_type. Custom Post Type is a custom post type that I created. If I just do a curl on posts the unset content is removed but if I do the version with ?type=custom_post_type the unset values still show up.

I am assuming that the var dump is not working on the /posts?type=custom_post_type. I just do not know why or if there is something specific I need to add to the function that you wrote above to make it work with specific post types.

This comment thread is closed. If you have important information to share, please contact us.