最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rest api add post meta

programmeradmin2浏览0评论

I want to show tow post meta in one rendered field rest api

my fields are 1- folder_path 2- file_name call example website/folderpath/filename.ext

i want to show it everywhere in 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/posts wp-json/wp/v2/search wp-json/wp/v2/posts/ etc..

thank you

I want to show tow post meta in one rendered field rest api

my fields are 1- folder_path 2- file_name call example website/folderpath/filename.ext

i want to show it everywhere in 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/posts wp-json/wp/v2/search wp-json/wp/v2/posts/ etc..

thank you

Share Improve this question asked Nov 8, 2019 at 20:19 arbfontsarbfonts 1
Add a comment  | 

1 Answer 1

Reset to default 0

You'll want to use the field and the post type. You'll add the following to your functions.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 );
        },
    ) );
} );
  1. add's fields to REST API
  2. change <post-type> to your specific post-type
  3. set the field name for the API and return the actual field itself for it (in this specific case, I just left the field_name as the meta name)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论