1. 程式人生 > 其它 >WordPress REST API中增加自定義欄位的顯示

WordPress REST API中增加自定義欄位的顯示

技術標籤:wordpress小程式wordpress

在做WordPress小程式編輯器的時候,遇到了需要自定義一些文章的欄位,但是通過REST介面訪問,發現meta裡面的值時空的,

不應該啊,既然wordpress有這個欄位,為什麼沒有值出來呢,去找找文件吧,果然找到:https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/

需要寫個小外掛,把欄位的show_in_rest設定為true,經過設定,完美呈現。

<?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';
$meta_args = array( // Validate and sanitize the meta value.
    // Note: currently (4.7) one of 'string', 'boolean', 'integer',
    // 'number' must be used as 'type'. The default is 'string'.
    'type'         => 'string',
    // Shown in the schema for the meta key.
    'description'  => 'A meta key associated with a string meta value.',
    // Return a single value of the type.
    'single'       => true,
    // Show in the WP REST API response. Default: false.
    'show_in_rest' => true,
);
register_meta( $object_type, 'my_meta_key', $meta_args );