Tagged: custom content types, fields, json, rest api
- This topic has 2 replies, 3 voices, and was last updated 4 years, 4 months ago by
Ico.
-
AuthorPosts
-
-
February 11, 2016 at 12:08 am #5904
RachelMemberHi all!
I figured I’d post this here in case someone else might find this useful.
As you may know, I am using Piklist to create some custom fields and serving them using the REST API. I would like a way to automagically monitor what Piklist fields are available per content type and include those in my API. This way, I won’t have to manually update the API every time a field is added.
Are there any functions that can monitor fields created using Piklist or a recommended way of doing so?
Here’s how I currently add fields to the API for a custom content type called ‘homepage’:
add_action('rest_api_init', 'my_rest_api_init'); function my_rest_api_init() { // This is where we add the custom fields to the REST API // More docs: http://v2.wp-api.org/extending/modifying/ $meta = array( 'custom_field_a', 'custom_field_b', 'custom_field_c' ); foreach ($meta as $meta_key) { register_api_field('homepage', $meta_key, array( 'get_callback' => 'get_registered_meta', 'update_callback' => 'update_registered_meta', 'schema' => null ) ); } } function get_registered_meta( $object, $field_name, $request ) { return get_post_meta( $object[ 'id' ], $field_name, true ); } function update_registered_meta( $value, $object, $field_name ) { if ( ! $value || ! is_string( $value ) ) { return; } return update_post_meta( $object->ID, $field_name, strip_tags( $value ) ); }Thanks again!
Rachel -
February 12, 2016 at 2:02 pm #5922
SteveKeymaster@rcantor– You can use the WordPress function get_post_custom(). It pulls EVERY custom field. Not just the ones created by Piklist.
-
October 2, 2017 at 10:33 am #8404
IcoMemberRachel, thanks for sharing your code snippet. If you made it working, can you share some more code? I’m trying to use WP as a REST backend for SPA and there are not much up-to-date examples on using the WP Resti API with custom meta, custom posttypes and theme options.
-
-
AuthorPosts
- You must be logged in to reply to this topic.