0

I have some post meta entries which I like to delete from the database. The delete_post_meta() function seems the way to go:

delete_post_meta( int $post_id, string $meta_key, mixed $meta_value = '' )

The problem: I have many entries with the same meta_key, so I'd like to specify the rows to be deleted by meta_value. But, the meta_value is serialized data. So how do I use delete_post_meta() to delete the post_meta by a specific value of the specialized data?

For example, the serialized data:

a:6:{s:2:"id";s:1:"1";s:4:"name";s:3:"PM1";s:5:"email";s:19:"[email protected]";s:3:"url";s:24:"https://example.nl/";s:4:"paid";s:1:"0";s:4:"city";s:9:"amsterdam";}

How do I delete by serialized ID value?

1 Answer 1

0

Try below code to delete the post_meta by a specific value of the specialized data:

$args = array(
    'post_type' => 'post',
    'meta_key' => 'any-meta-key',
    'posts_per_page' => -1
 );

$query = new WP_Query( $args );
if($query->have_posts()){
    while($query->have_posts()){
        $query->the_post();
        $get_ID = get_post_meta($post->ID, 'any-meta-key', true);

        // Change the id value that you want to delete 
        if ( !empty($get_ID['id']) && $get_ID['id'] == '1' ) {
            delete_post_meta($post->ID,'any-meta-key',$get_ID);
        }
    }
}

Don't forget to update the test meta key by your meta key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.