我在使用REST API将元素添加到post meta中的user_id数组时遇到问题。这与未与REST API集成时效果很好,但是当我通过API执行此操作时,我添加到数组中的新值以及post meta中的ID列表始终覆盖以前的值,而不是将其添加到列表中。我相信这很简单:你的帮助真的很棒!!!
由于
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
};
}