Viewing 2 reply threads
  • Author
    Posts
    • #5904
      Rachel
      Member

      Hi 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

    • #5922
      Steve
      Keymaster

      @rcantor– You can use the WordPress function get_post_custom(). It pulls EVERY custom field. Not just the ones created by Piklist.

    • #8404
      Ico
      Member

      Rachel, 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.

Viewing 2 reply threads
  • You must be logged in to reply to this topic.