rest api add post meta

时间:2019-11-08 作者:arbfonts

我想在一个渲染字段rest api中显示两个post meta

我的字段是1-folder\\u path 2-file\\u name call example website/folderpath/filename。外景

我想在rest api中到处显示它

add_action( \'rest_api_init\', \'create_api_posts_meta_field\' );

function create_api_posts_meta_field() {

 // register_rest_field ( \'name-of-post-type\', \'name-of-field-to-return\', array-of-callbacks-and-schema() )
 register_rest_field( \'post\', \'download_link\', array(
 \'get_callback\' => \'get_post_meta_for_api\',
 \'schema\' => null,
 )
 );
}

function get_post_meta_for_api( $object ) {
 //get the id of the post object array
 $post_id = $object[\'id\'];

 //return the post meta
 return get_post_meta( $post_id );
}
wp-json/wp/v2/postswp-json/wp/v2/searchwp-json/wp/v2/posts/etc。。

非常感谢。

1 个回复
SO网友:RMH

您需要使用字段和帖子类型。您将向函数中添加以下内容。php

add_action( \'rest_api_init\', function () {
    register_rest_field( \'<post-type>\', \'folder_path\', array(
        \'get_callback\' => function( $post_arr ) {
            return get_post_meta( $post_arr[\'id\'], \'folder_path\', true );
        },
    ) );

    register_rest_field( \'<post-type>\', \'file_name\', array(
        \'get_callback\' => function( $post_arr ) {
            return get_post_meta( $post_arr[\'id\'], \'file_name\', true );
        },
    ) );
} );
将的字段添加到REST API更改<post-type> 对于特定的post类型,设置API的字段名称,并为其返回实际字段本身(在这种特定情况下,我只是将字段名称保留为元名称)