How to delete values of a wordpress post_meta_value

797 views Asked by At

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

2

There are 2 answers

0
Biplob Ahmed On

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 );
2
Morteza Barati On

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);