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

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)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.