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:"/";s:4:"paid";s:1:"0";s:4:"city";s:9:"amsterdam";}
How do I delete by serialized ID value?
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?
Share Improve this question asked May 26, 2020 at 20:32 PepsPeps 531 silver badge7 bronze badges1 Answer
Reset to default 0Try 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.