The delete_meta() WordPress PHP function is used to delete post meta data by using its meta ID.
Usage
The usage of the delete_meta() function is quite straightforward. You just need to pass the meta ID as the parameter. Here’s an example:
delete_meta(123);
In this case, ‘123’ is the meta ID of the post meta data we want to delete.
Parameters
- $mid (int) – The ID of the meta data you want to delete. It is required.
More information
See WordPress Developer Resources: delete_meta()
This function is a part of WordPress core and is generally not depreciated. The source code can be found in wp-includes/post.php
.
Examples
Delete Post Meta
This code deletes a specific post meta by its ID.
// The ID of the meta data we want to delete $meta_id = 123; // Delete the post meta data delete_meta($meta_id);
Delete Multiple Post Metas
This code deletes multiple post metas using their respective IDs.
// The IDs of the meta data we want to delete $meta_ids = array(123, 124, 125); // Loop through each ID and delete the corresponding post meta data foreach ($meta_ids as $id) { delete_meta($id); }
Conditional Deletion of Post Metas
This code deletes a post meta only if it exists.
// The ID of the meta data we want to delete $meta_id = 123; // Check if the post meta data exists before deleting if (metadata_exists('post', $post_id, $meta_key)) { delete_meta($meta_id); }
Delete Post Meta and Handle Errors
This code deletes a post meta and handles any errors that may occur.
// The ID of the meta data we want to delete $meta_id = 123; // Try to delete the post meta data and check if it was successful if (!delete_meta($meta_id)) { echo 'Failed to delete post meta data'; } else { echo 'Post meta data deleted successfully'; }
Delete Post Meta on Post Deletion
This code deletes a post’s meta data when the post itself is deleted.
// The ID of the post we want to delete $post_id = 123; // Delete the post wp_delete_post($post_id, true); // Get all the post's meta data $meta_data = get_post_meta($post_id); // Delete each meta data foreach ($meta_data as $meta_id => $meta_value) { delete_meta($meta_id); }