{"id":1424,"date":"2017-03-13T17:40:29","date_gmt":"2017-03-13T08:40:29","guid":{"rendered":"https:\/\/n8finch2024.local\/?p=1424"},"modified":"2019-06-30T06:59:58","modified_gmt":"2019-06-29T21:59:58","slug":"getting-post-meta-wp-rest-api","status":"publish","type":"post","link":"https:\/\/n8finch2024.local\/getting-post-meta-wp-rest-api\/","title":{"rendered":"Getting Post Meta for the WP REST API"},"content":{"rendered":"

My friend and I are working on a little side project. It’s a job posting site for an industry we’re familiar with:\u00a0ESL jobs around the world.\u00a0While this project could be seen as “just another job board”, we’re hoping to add some features that will make it fun to use and valuable for schools and recruiters. I of course want to build it on WordPress, but to get a\u00a0some of the functionality I want, I need to expose some post meta to the WP REST API.<\/p>\n

In researching how to do this, I quickly found out that the WP REST API doesn’t naturally expose post or user meta.\u00a0As with most things WP REST API, you don’t have to go too far down the rabbit hole before you find\u00a0a practical article written by\u00a0the<\/em> Josh Pollock. While the register_api_field<\/code>\u00a0function isn’t in use anymore, the register_rest_field<\/code>\u00a0function is, so this article<\/strong><\/a> and that function<\/strong><\/a> were all I needed to get going.<\/p>\n

<\/p>\n

Here’s the code for getting all post meta for the WP REST API:<\/p>\n

\r\nadd_action( 'rest_api_init', 'create_api_posts_meta_field' );\r\n\r\nfunction create_api_posts_meta_field() {\r\n\r\n \/\/ register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )\r\n register_rest_field( 'post', 'post-meta-fields', array(\r\n 'get_callback' => 'get_post_meta_for_api',\r\n 'schema' => null,\r\n )\r\n );\r\n}\r\n\r\nfunction get_post_meta_for_api( $object ) {\r\n \/\/get the id of the post object array\r\n $post_id = $object['id'];\r\n\r\n \/\/return the post meta\r\n return get_post_meta( $post_id );\r\n}\r\n<\/pre>\n

The comments in there are self explanatory, but this also allows me to get the custom fields for any custom post type as well (Josh’s example is a jedi<\/code>\u00a0custom post type, which is way cooler than my practical job-postings<\/code>\u00a0custom post type \ud83d\ude42 ).\u00a0That way, I can save whatever information in the custom fields of my job-postings<\/code>\u00a0custom post type I need, like:<\/p>\n