How to add custom meta data to WordPress REST API

The WordPress REST API is a very neat thing. I'm using it to pull my To-Do list into my Firefox Start Page, which I find totally awesome 🤩

If you're using custom post meta data is not as straight forward. For some reason the meta data is not exposed by default when you query posts via the REST API. Or at least didn't work for my meta data, perhaps I did store them wrong 🤪

In any case, here's the query I tried without luck /wp-json/wp/v2/posts

How do you expose custom data?

You can expose anything you want, be it post metadata, computed data, anything really.

In the snippet below I'm returning a boolean based on the post metadata called todo__done. Plus I'm also exposing html-stripped version of the post content as clean-title.

add_action( 'rest_api_init', 'create_api_posts_meta_field' );

function create_api_posts_meta_field() {
    register_rest_field( 'post', 'done', array(
           'get_callback'    => 'get_post_meta_done',
           'schema'          => null,
        )
    );

    register_rest_field( 'post', 'clean-title', array(
      'get_callback'    => 'get_post_clean_title',
      'schema'          => null,
      )
    );
}

function get_post_meta_done( $object ) {
    $post_id = $object['id'];

    return get_post_meta( $post_id, 'todo__done', true) === "1" ? true : false;
}

function get_post_clean_title( $object ) {
    $post_id = $object['id'];

    return wp_strip_all_tags(get_the_content($post_id));
}Code language: PHP (php)

How to use the newly exposed properties?

Simply list it as a _fields and it will be on the returned JSON.

/wp/v2/posts&_fields[]=done&_fields[]=clean-title

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *