I try to save with wp-json my custom post types meta data but does not works in my case

I create my custom post type with jjgrainger's class as it follows

$arguments = array(
        'public'       => true,
        'show_in_rest' => true,
    );

    $survey = new PostType('survey', $arguments);
    $survey->register();

    register_meta( 'survey', 'survey_data', array(
        'show_in_rest' => true,
        'single' => true
    ) );

    return $survey;

but when I save the following structure

 post: {
                    title: "Title",
                    content: "some content",
                    status: 'publish',
                    id: null,
                    survey_data: null,
                    meta: {
                        survey_data: [{'some': 'asdasd'}, {'some':'ssdfs'}]
                    }
                },

the post will be created but not the meta data

up vote 0 down vote accepted

The register_meta() function is defined like so:

function register_meta( $object_type, $meta_key, $args, $deprecated = null )

And the $object_type (as of now) has to be post for all post types. So use this:

register_meta( 'post', 'survey_data', ... )

See the // {comments} in the code below, which I copied from here:

<?php
// The object type. For custom post types, this is 'post';
// for custom comment types, this is 'comment'. For user meta,
// this is 'user'.
$object_type = 'post';
$args1 = array( ... );
register_meta( $object_type, 'my_meta_key', $args1 );

UPDATE

If you'd like to limit the meta to a certain post type, use the object_subtype parameter like so: (that parameter was added in WordPress version 4.9.8)

// Add survey_data meta support to `survey` post type in REST API.
register_meta( 'post', 'survey_data', array(
  'show_in_rest'   => true,
  'object_subtype' => 'survey',
  ...
) );

// Add survey_data meta support to `my_cpt` post type in REST API.
register_meta( 'post', 'survey_data', array(
  'show_in_rest'   => true,
  'object_subtype' => 'my_cpt',
  ...
) );

And as you can see, just duplicate the same register_meta() call for other post types. But the $object_type needs to be post, even for Pages (page post type).

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.