Issue adding elements to an array in post meta using REST API
-
Hi,
I have a problem adding elements to an array of user_ids in post meta using the REST API. This works well when not integrated with the REST API, but when I do it through the API, the new value I add to the array with the list of IDs in post meta always overwrite the previous value, rather than add it in the list. I am sure this is something really simple: your help would really GREAT!!!
Thanks
register_rest_field( 'post', 'nb_post_registered_user_liked', array( 'get_callback' => 'nb_get_post_registered_user_liked', 'update_callback' => 'nb_update_post_registered_user_liked', 'delete_callback' => null, 'schema' => $nb_post_registered_user_liked_schema // defined separately ) function nb_get_post_registered_user_liked( $object, $field_name, $request ) { return get_post_meta( $object['id'], 'nb_post_liked_user_ids', true ); // to test post meta } function nb_update_post_registered_user_liked( $value, $object, $field_name ) { $nb_post_liked_user_ids_meta = null; $user_key = null; $user_id = get_current_user_id(); $nb_post_liked_user_ids_meta = get_post_meta( $object->ID, 'nb2_post_liked_user_ids', true ); if ( count( $nb_post_liked_user_ids_meta ) != 0 ) { $nb_post_liked_user_ids_meta = $nb_post_liked_user_ids_meta[0]; } if ( !is_array( $nbu_post_liked_user_ids ) ) { $nb_post_liked_user_ids_meta = array(); } $user_key = array_search( $user_id, $nb_post_liked_user_ids_meta ); if ( !$user_key ) { $nb_post_liked_user_ids_meta['user-' . $user_id] = $user_id; $nb_post_liked_user_ids_meta[] = $user_id; // tried also this way... update_post_meta( $object->ID, 'nb_post_liked_user_ids', $nb_post_liked_user_ids_meta ); return nb_post_liked_user_ids_meta; // to test }; }
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘Issue adding elements to an array in post meta using REST API’ is closed to new replies.