If you’re supplying the request data/body like so, which is an array of metadata:
{ metadata: { wishlist_array: "add this", foo: "bar baz" } }
and you want to update only the wishlist_array
metadata, then you could do:
// In your case, $field_value is the `metadata` value and $data is a WP_Post object.
'update_callback' => function( $field_value, $data ){
if ( is_array( $field_value ) && isset( $field_value['wishlist_array'] ) ) {
update_post_meta( $data->ID, 'wishlist_array', $field_value['wishlist_array'] );
return true;
}
}
Or if you want to update all metadata (or all fields supplied in that metadata
array), then this would do it:
// In your case, $field_value is the `metadata` value and $data is a WP_Post object.
'update_callback' => function( $field_value, $data ){
if ( is_array( $field_value ) ) {
foreach ( $field_value as $key => $value ) {
update_post_meta( $data->ID, $key, $value );
}
return true;
}
}
And regarding this question: “// How can I print or log the $data content??“, you could do var_dump( $data );
and check the PHP error logs — or wp-content/debug.log
if it is enabled.
Some Notes
-
In the
update_callback
function, the$field_value
is the value of themetadata
parameter; whereas the$data
is the data object — this is equivalent to the$data
in theget_callback
function, except that in theupdate_callback
function, the$data
is not an array. -
You may also want to check this sample code on the REST API handbook.
-
The examples above are basic examples and as stated on the REST API handbook, carefully consider what permissions checks or error handling may be required for your specific field.
-
With
update_field()
(ACF), you could also use$data->ID
as the third parameter passed toupdate_field()
.