plugin development - register_meta not showing custom post type metabox data in rest api

admin2025-01-08  7

I have added a custom post type and I want to expose the custom field value in the rest api. As per the docs register_meta can be used.

I have created a custom post meta box using the wordpress way. It works fine but not getting shown in the rest api. I belive that I have to pass array

add_action( 'rest_api_init', 'qrcode_register_posts_meta_field' );

function qrcode_register_posts_meta_field(){
  $meta_args = array( // Validate and sanitize the meta value.
    'type'         => 'array',
    
    'description'  => 'A meta key associated with a string meta value.',
   
    'single'       => true,
   
    'show_in_rest' => array(
      'schema'=> array(
        'type'=> 'array',
        'items'=> array(
          'type'=> 'string',
        ),
      ),
    ),
);
  register_meta( 'post', 'qrcode_qr-code-type', $meta_args );
}

I have added a custom post type and I want to expose the custom field value in the rest api. As per the docs register_meta can be used.

I have created a custom post meta box using the wordpress way. It works fine but not getting shown in the rest api. I belive that I have to pass array

add_action( 'rest_api_init', 'qrcode_register_posts_meta_field' );

function qrcode_register_posts_meta_field(){
  $meta_args = array( // Validate and sanitize the meta value.
    'type'         => 'array',
    
    'description'  => 'A meta key associated with a string meta value.',
   
    'single'       => true,
   
    'show_in_rest' => array(
      'schema'=> array(
        'type'=> 'array',
        'items'=> array(
          'type'=> 'string',
        ),
      ),
    ),
);
  register_meta( 'post', 'qrcode_qr-code-type', $meta_args );
}
Share Improve this question edited Jan 10, 2021 at 16:10 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Jan 10, 2021 at 14:32 user145078user145078
Add a comment  | 

2 Answers 2

Reset to default 0

Found: I forgot to enable the Custom Fields for the custom post type even if the meta boxes were programmatically created.

For those programmatically creating the CPT, be sure to also support 'custom-fields' in your post type, as noted in https://developer.wordpress.org/reference/functions/register_post_meta/#user-contributed-notes

register_post_type( 'book', array(
    'supports' => array( 'title', 'editor', 'custom-fields', ...),
     // Make sure you add custom-fields here ^^^^^^^^^^^^^
    )
);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736270394a1425.html

最新回复(0)