Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress API V2 custom fields with custom post types

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?

like image 793
Graeme Paul Avatar asked Nov 26 '25 09:11

Graeme Paul


1 Answers

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 );
}
like image 101
d79 Avatar answered Nov 28 '25 15:11

d79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!