Jetpack JSON Api – outputting custom fields

Instead of using rss to retrieve data from a wordpress site I wanted to try out the Jetpack JSON API, aka WordPress Rest api. I came across some smallish challenges, so just wanted to write a quick post with the solution for those getting stuck on the same.

Problem one: The json api doesn’t display customfields as default.
Problem two: Problems retrieving data from a wordpress network (multisite)
Problem three: Weight

Problem one

We use customfields for frontpage images and to give our posts better metadata, but by default these are hidden from the public api.
To solve it, turn on Jetpack Json api, then add the following code to your WP theme functions.php:

As you can see, you have to manually add the fields you want exposed.

(Via Stackexchange)

Problem two

Error on multisite. The format to call the json api looks like this https://public-api.wordpress.com/rest/v1/sites/pappmaskin.no/posts/?pretty=true&number=3, but if you’re running a multisite install and change pappmaskin.no to pappmaskin.no/urltosubsite/ then the request will fail. Luckily the solution was simple: Just urlencode the site url to pappmaskin.no%2Furltosubsite%2F. (Via alpha1 on Stackexchange)

It is also possible to use the Jetpack Site ID instead of the encoded url. That ID is returned in most queries to the api, in the site_ID field. (Thanks to Jeremy Herve, via WordPress.org). The only way to get to a subsite site_ID (as far as I have found), is to actually do the urlencode trick first.

So for this site, this will also work.

https://public-api.wordpress.com/rest/v1/sites/6464046/posts/?pretty=true&number=3

Problem three: Weight

The posts endpoint outouts (almost) all the content and data associated with your posts, which might be a bit overkill. The api actually lets you filter exactly the fields you need. Like so:

https://public-api.wordpress.com/rest/v1/sites/pappmaskin.no/posts/?pretty=true&number=3&category=diy&fields=title,excerpt,URL,date,metadata

Which gives you a nice and tidy little JSON package:

Av Morten Skogly

Creator of Things

Legg igjen en kommentar

Din e-postadresse vil ikke bli publisert. Obligatoriske felt er merket med *