How can I include meta info when adding a new post via REST?

26 Views Asked by At

I am trying to include meta info when I create a new post via the REST API however it never seems to save the meta information. Basic fields like title, author & status are adding fine but not meta fields.

I include the following code to add the endpoints for the meta data and a function to add the meta on insert.

//register meta
add_action( 'rest_api_init', 'sapi_register_rest_meta');
function sapi_register_rest_meta(){
    register_post_meta( 'post', 'sharepoint_list_id', array(
        'type' => 'string',
        'description' => 'List ID',
        'single' => true,
        'show_in_rest' => array(
            'schema' => array(
                'type'    => 'string',
                'default' => '',
            ),
        ),
    ));
    register_post_meta( 'post', 'sharepoint_list_item_id', array(
        'type' => 'string',
        'description' => 'List Item ID',
        'single' => true,
        'show_in_rest' => array(
            'schema' => array(
                'type'    => 'string',
                'default' => '',
            ),
        ),
    ));
}

//save meta on rest instert
add_action( "rest_insert_post", function ( \WP_Post $post, $request, $creating ) {
    $metas = $request->get_param( "meta" );
    if( is_array( $metas ) ) {
        foreach( $metas as $name => $value ) {
            update_post_meta( $post->ID, $name, $value );
        }
    }
}, 10, 3 );

The body of the data in JSON form looks like this:

{
    "title": "Adding a new post from SharePoint",
    "status": "draft",
    "author": "1043",
    "meta": {
        "sharepoint_list_id": "99999999-8888-7777-6666-555555555555",
        "sharepoint_list_item_id": "12"
    }
}

If I manually add the metadata in WordPress and publish the post I can see the data in the response when I go to https://apitest.somedomain.com/wp-json/wp/v2/posts/193434

What am I missing?

0

There are 0 best solutions below