WP API响应未显示我注册的元数据

时间:2021-04-30 作者:Grzes Slania

我正在尝试从自定义帖子类型获取元数据splash_location 然而,这并没有出现在我的回答中。我已注册metatagsplash_location_title 但它没有显示在我的JSON请求中。

function splash_location_custom_post_type() {
  register_post_type(\'splash_location\',
    array(
      \'labels\'      => array(
        \'name\'          => __(\'Locations\', \'textdomain\'),
        \'singular_name\' => __(\'Location\', \'textdomain\'),
      ),
      \'supports\' => array( \'title\', \'custom-fields\' ),
      \'menu_icon\'   => \'dashicons-admin-page\',
      \'public\'      => true,
      \'has_archive\' => true,
      \'show_in_rest\' => true,
     )
  );
}
add_action(\'init\', \'splash_location_custom_post_type\');

$meta_args = array( 
    \'type\'         => \'string\',
    \'description\'  => \'A meta key associated with a string meta value.\',
    \'single\'       => true,
    \'show_in_rest\' => true,
);
register_meta( \'splash_location\', \'splash_location_title\', $meta_args );



//Code in my block file to get splash_location data   
const getLocationPosts = () => axios
    .get(\'/wp-json/wp/v2/splash_location/\')
    .then(response => {
        const { data } = response
        console.log(data)
    })

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

对于帖子(帖子、页面和自定义帖子类型),第一个参数register_meta() 始终是post 要设置自定义帖子类型,请使用object_subtype 第三个参数中的参数如下:

$meta_args = array(
    \'object_subtype\' => \'splash_location\', // the post type
    \'type\'           => \'string\',
    \'description\'    => \'A meta key associated with a string meta value.\',
    \'single\'         => true,
    \'show_in_rest\'   => true,
);
register_meta( \'post\', \'splash_location_title\', $meta_args );
或者你可以用register_post_meta() 它接受post类型作为第一个参数:

$meta_args = array(
    \'type\'         => \'string\',
    \'description\'  => \'A meta key associated with a string meta value.\',
    \'single\'       => true,
    \'show_in_rest\' => true,
);
register_post_meta( \'splash_location\', \'splash_location_title\', $meta_args );
因此,在现有代码中,只需替换register_meta 具有register_post_meta..