3

I'm trying to add my custom posts to the Wordpress API, which also have custom fields.

I can view the custom posts types on the API via, /wp-json/wp/v2/fruit.

But the custom fields aren't displaying, how do you add them to the API?

3
  • wordpress.org/plugins/acf-to-rest-api Commented Dec 4, 2017 at 14:38
  • or thats the way I did it - there might be others, but this was literally at the click of a button. Commented Dec 4, 2017 at 14:39
  • @Stender that didn't work for me, i'm not using the Advanced Custom Fields plugin Commented Dec 4, 2017 at 15:04

1 Answer 1

5

Take a look at "Extending the REST API / Modifying Responses", and in particular at register_rest_field.

Check out this example:

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', 'post-meta-fields', 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 );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.