如何使用序列化数组数据库Wordpress进行CRUD操作?

How to work with serialize array database Wordpress to make CRUD operation?

我在 metauser table 中有数据,如下所示。如您所见,数据采用序列化数组的形式。如何推送数组数据?我想在元书签中保存 post id。但是,如果我改用 add_user_meta(),它会在新行中创建数据,而不是在值中添加数据(因此 1 个用户中将有 2 个具有不同值的元书签)。如果我使用 update_user_meta() 它只是替换旧的新值,而不是添加(推送)数组数据。如何向元值添加新数据(数组)?

就像下面的示例图片一样,这是来自插件 ulike WordPress 的 post_statuscomment_status 的元数据。我觉得当有新的post或者有新评论的时候,这个值也会根据关联的id增加。

[

如果有不正确或不合table的词,请自由编辑此问题。

谢谢!

您可以使用 get_user_meta 函数获取值。

$post_status = get_user_meta( $user_id, 'post_status', true );

Now modify $post_status array as per your requirement. and update after it.

update_user_meta( $user_id, 'post_status', $post_status );

记住 WordPress 使用 maybe_serializemaybe_unserialize 来保存元表并从中获取值。

要将数组作为用户元数据存储在 Wordpress 数据库中,您可以使用 PHP serialize() 函数。在此示例中,将为当前用户存储一个数组(如您的屏幕截图所示)。

$bookmark = array(
    0 => 3058,
);
update_user_meta( get_current_user_id(), '_bookmark_article', serialize($bookmark) );

要修改序列化数组,您可以使用 PHP unserialize() 函数。在此示例中,将检索、修改和更新用户元 _bookmark_article

// retrieves the value of the user meta "_bookmark_article"
$bookmark_article = get_user_meta( get_current_user_id(), '_bookmark_article', true );
// convert value to array
$bookmark_article = unserialize( $bookmark_article );

// adds a value to the array
$bookmark_article_updated = $bookmark_article_array[] = 3445;
// updates an array value based on the key
$bookmark_article_updated = $bookmark_article_array[0] += 50;

// updates the value of the user meta "_bookmark_article"
update_user_meta( get_current_user_id(), '_bookmark_article', serialize($bookmark_article_updated) );