I have registered a post type and can create new posts of that type via the rest api. however, i cannot seem to add any post meta i.e. custom fields.
here is the data i send:
$data = array(
"title" => $post->name,
"content" => $record->content,
"status" => "draft",
"author" => "1",
"meta" => array( "test" => "test" )
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_USERPWD, "USER:PASSWORD");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec( $ch );
curl_close( $ch );
to be sure, i have also created a specific meta, although i don't know if this even works or does anything.
add_action( 'init', 'register_meta_function' );
function register_meta_function() {
$meta_args = array(
'type' => 'string',
'description' => 'test',
'single' => true,
'show_in_rest' => true,
);
register_meta( 'POST_TYPE', 'test', $meta_args );
}
with a post type, i can at least see in the menu, that it has been created, but i cannot see that meta field anywhere.
does anyone have experience with the wordpress rest api and knows where the problem is?
Try replacing:
add_action( 'init', 'register_meta_function' );
with
add_action( 'rest_api_init', 'register_meta_function' );
Then test your update via the REST API to see if the meta field value appears on the edit page for the post.
Your options for displaying the meta field value when viewing the post (on the front-end) depend on whether you are using a client-side solution (e.g. enqueued scripts, the data module) or a server-side solution (e.g. the_content filter hook).
Updating meta values for custom post types has to be handled differently compared to the WordPress core post type. The solution to the problem could be in this Stack Exchange question: Add post meta fields, when creating a post using WordPress' REST API, which was borrowed from this question. The solution is outlined below. In the function below, replace the text CUSTOM_POST_TYPE with the name of your custom post type.
/**
* Update post meta for CUSTOM_POST_TYPE.
*
* @see https://developer.wordpress.org/reference/hooks/rest_insert_this-post_type/
* @see https://developer.wordpress.org/reference/functions/update_post_meta/
*/
function post_meta_update( \WP_Post $post, \WP_REST_Request $request, bool $creating ): void {
$metas = $request->get_param( 'meta' );
if ( is_array( $metas ) ) {
foreach ( $metas as $meta_name => $meta_value ) {
update_post_meta( $post->ID, $meta_name, $meta_value );
}
}
}
add_action( 'rest_insert_CUSTOM_POST_TYPE', 'post_meta_update', 10, 3 );