Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress json rest API to get custom field data

I am currently using the JSON REST API (WP API) plug-in to get my post and page data.

I have noticed that none of my custom field data is returned in the json, and looking at the routes, i don't think i can obtain these.

Any ideas via the current plug-in, or how I can accomplish this otherwise?

like image 750
Simon Davies Avatar asked Sep 29 '22 04:09

Simon Davies


2 Answers

If you are using 'advanced custom fields' - until something more official is decided, you can use this plugin: https://github.com/times/acf-to-wp-api (and now on the shelf in standard wp plugin area too.)

It will include the custom fields under acf: [], in your json structure.

like image 149
sheriffderek Avatar answered Oct 12 '22 10:10

sheriffderek


To grab a custom field value using native WP functions only, add the following to your functions.php

function my_rest_prepare_post( $data, $post, $request ) {
  $_data = $data->data;
  $_data[$field] = get_post_meta( $post->ID, 'my_custom_field_key', true );
  $data->data = $_data;
  return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );

Replace 'my_custom_field_key' with your custom field key name.

For multiple fields:

function my_rest_prepare_post( $data, $post, $request ) {
  $_data = $data->data;
  // My custom fields that I want to include in the WP API v2 responce
  $fields = ['writer', 'publisher', 'year', 'youtube_link'];

  foreach ( $fields as $field ) {
    $_data[$field] = get_post_meta( $post->ID, $field, true );
  }

  $data->data = $_data;
  return $data;
}

add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
like image 24
Hani Avatar answered Oct 12 '22 09:10

Hani