DEV Community

Cover image for WordPress Post Metadata in RestAPI
Keramot UL Islam
Keramot UL Islam

Posted on • Originally published at blog.abmsourav.com

WordPress Post Metadata in RestAPI

WordPress has Rest API support since 2016. It’s designed to reach other paradigms. Unfortunately, WordPress doesn’t provide Rest API support for metadata by default. But we can add metadata in Rest API. There are 3 different ways to add metadata in Rest API.

1. Add Rest API support while Registering metadata: The simplest way of adding metadata in Rest API is to add support while you’re registering metadata. You can do it by adding show_in_rest as true in the arguments.

$meta_args = array( 
    'type'         => 'string',
    'single'       => true,
    'show_in_rest' => true,
);
register_meta( 'post', 'my_meta_keys', $meta_args );
Enter fullscreen mode Exit fullscreen mode



2. Add metadata in Rest API response object: Most of the time you are going to use this way.

// callback function
function my_get_post_meta() {
    // get_post_meta( post_id, meta_key[optional], single[optional] )
    $post_meta = get_post_meta( 15 );
    $meta = [];
    foreach( $post_meta as $meta_key => $meta_value ) {
        $meta[$meta_key] = $meta_value[0];
    }
    return $meta;
}

function meta_rest_api() {
    register_rest_field( 'post', 'my_meta', array(
        'get_callback'      => 'my_get_post_meta',
        // 'update_callback'=> null,
        // 'schema'         => null
    ) );
}
add_action( 'rest_api_init', 'meta_rest_api' );
Enter fullscreen mode Exit fullscreen mode

Now, what’s happing here? Well, in the callback function I’m getting all metadata from a post and adding them in an array as key-value pair. Then register_rest_field is doing the magic. WordPress provides this function to add data in the Rest API response object. It also knows in which route to put data. You also can provide update_callback and schema if necessary.
Now you will find all those metadata in https://domain/wp-json/wp/v2/posts/15 under my_meta property.
Please note that I have provided the post id 15, in your case the post id will be different.

3. Add metadata in a custom route: Sometimes you need to add post metadata in a custom route. Sometimes it's may necessary for big projects.
Click Here to read the full article.

Similar Post:

Top comments (0)