WP REST API Update post meta using curl

Kinder Cappy Source

I want to update post meta using curl from bash.

The authorization is working fine with the Basic Authentication and I am able to update the post meta with a predefined string in the register_rest_field function.

curl -X POST  -H 'content-type: application/json' -d '{"score":10}'

This is the curl command being used. The REST API function that is being called is:

register_rest_field( 'custompost', 'post-meta-fields', array(
     'get_callback' => function ( $data ) {
       return update_post_meta(53,'website_name',$data->score);

I am not able to get the $data object and get the score property that is being passed in the curl command.

How to get the score property which is being passed as json data in the curl command?



answered 6 months ago Noman #1

As per the docs Using register_rest_field

The register_rest_field function is the most flexible way to add fields to REST API response objects. It accepts three parameters:

  1. $object_type: The name of the object, as a string, or an array of the names of objects for which the field is being registered. This may be a core type like “post”, “terms”, “meta”, “user” or “comment”, but can also be the string name of a custom post type.
  2. $attribute: The name of the field. This name will be used to define the key in the response object.
  3. $args: An array with keys that define the callback functions used to retrieve the value of the field (‘get_callback’), to update the value of the field (‘update_callback’), and to define its schema (‘schema’).

in your case $data would be an array, if not then try below code structure for Modifying Responses

add_action( 'rest_api_init', function () {
    register_rest_field( 'comment', 'karma', array(
        'get_callback' => function( $comment_arr ) {
            $comment_obj = get_comment( $comment_arr['id'] );
            return (int) $comment_obj->comment_karma;
        'update_callback' => function( $karma, $comment_obj ) {
            $ret = wp_update_comment( array(
                'comment_ID'    => $comment_obj->comment_ID,
                'comment_karma' => $karma
            ) );
            if ( false === $ret ) {
                return new WP_Error(
                  __( 'Failed to update comment karma.' ),
                  array( 'status' => 500 )
            return true;
        'schema' => array(
            'description' => __( 'Comment karma.' ),
            'type'        => 'integer'
    ) );
} );

comments powered by Disqus