0

everyone

I would like to delete a value from the postmeta in my wordpress installation - and not a complete metavalue, but only part of the content in it.

e.g. metakey = test metavalue = abba; dancing; queen;

and the "dancing" should be thrown out. With update_post_meta and delete_post_meta I only manage to delete the complete metavalue or metakey. update_post_meta( $id, 'test', $dancing); delete_post_meta( $id, 'test', $dancing); dont work :-(

how can i remove only part of it?

lg yeah

JSt.
  • 1
  • 1

2 Answers2

0

I think it works. First I get the value of the previous postmeta. Then we change it and finally save it in our post. The order is as follows:

$test_meta_key = get_post_meta($post_id, 'meta_key');

$test_meta_key = str_replace('dancing', '', $test_meta_key);

update_post_meta($post_id, 'meta_key', $test_meta_key);
Morteza Barati
  • 329
  • 3
  • 11
  • Hi Morteza, thank you for your comment. I thought that update_post_meta would automatically serialize the value, so that the original values ​​would no longer be in the postmeta if I remove it with str_replace & then save it with update_post_meta? i have read it here: https://wordpress.stackexchange.com/questions/290189/inserting-serialized-value-into-wp-postmeta-using-update-post-meta or am I misunderstanding something? kind regars Jo – JSt. May 30 '22 at 08:59
  • hi @JSt. you're welcome I saw exactly the same behavior in that link. So for you, the update_post_meta function should automatically update the total value of a key, regardless of what the previous value was. So we need to first take the previous value and then change it and save it in the new value. What I saw in that link was that In their meta, the value was stored as an array, so they resent the value as a presentation to update_post_meta. We do the same in this. – Morteza Barati May 30 '22 at 09:47
0

just remove the dancing word from the desired metavalue. You don't have to serialize if meta value is an array, wordpress will automatically do it for you.

$post_id    = 1;
$metakey    = 'test'; 
$metavalue  = "abba; dancing; queen";
$metavalue  = "abba; queen"; // updated meta value
update_post_meta( $post_id, $metakey, $metavalue );

if $metavalue is array

$metavalue = [ "abba", "dancing", "queen" ];
$metavalue = [ "abba", "queen" ]; // updated meta value
update_post_meta( $post_id, $metakey, $metavalue );
Biplob Ahmed
  • 106
  • 4