Recently I was asked how to use WordPress API to get postmeta. The goal was to feed a tooltip in an independent web app related to the online user guide.
Sounds simple, right ? Well… not that much !
Approach
Turns out there’s no native WordPress API to get postmeta endpoint, and by default, postmeta isn’t included in the WordPress posts API response.
That sounded odd. I mean, postmeta is where we store so much useful data, so how come it’s not there? After some more digging, I stumbled on the rest_api_init action, which is fired when a REST API request is about to be served. That was the missing piece.
From that point, I just had to figure out how to hook into the post API response and include the meta fields. It turns out you can use register_rest_fields( ) to add your own fields to the API response. In this case, I created one called post_meta_fields and used a custom callback, get_post_meta_for_api, to return the actual postmeta.
Now let’s see how to use WordPress API to get postmeta
After all research, the code looks like this:
1 2 3 4 5 6 7 8 |
add_action( 'rest_api_init', function() { register_rest_field( 'post', 'post-meta-fields', array ( 'get_callback' => 'get_post_meta_for_api', 'schema' => null, ) ); } ); |
With this snippet, every post queried via the API will now include its associated meta fields under the post-meta-fields key.
Let’s test if we can now use WordPress API to get postmeta
It’s a GET API, so you can simply paste the url in your browser or you can even curl it in a console or terminal.
1 2 3 |
curl https://<your-site>/wp-json/wp/v2/posts/<the-post-id> |
Conclusion
This isn’t the only way to go about it, but for what I needed, this wordpress api get postmeta approach worked like a charm.
It’s a small change, but it opens up a lot of flexibility when integrating WordPress with external systems. This kind of tweak can be especially useful when building decoupled frontends, mobile apps, or any third-party service that relies on structured data from WordPress.