Using WordPress ‘delete_post_meta()’ PHP function

The delete_post_meta() WordPress PHP function deletes a post meta field for a given post ID. This function allows you to remove metadata based on key or both key and value. This way, you can avoid deleting duplicate metadata with the same key.

Usage

Here’s how you can generally use the delete_post_meta() function:

delete_post_meta($post_id, $meta_key, $meta_value);

If you have a post with ID 76, and you want to delete the metadata field ‘my_key’ with the value ‘Steve’, you would do it like this:

delete_post_meta(76, 'my_key', 'Steve');

Parameters

  • $post_id (int): Required. This is the ID of the post for which you want to delete the metadata.
  • $meta_key (string): Required. This is the name of the metadata you want to delete.
  • $meta_value (mixed): Optional. If provided, only the metadata rows that match this value will be deleted. It must be serializable if non-scalar. Default is an empty string (”).

More information

See WordPress Developer Resources: delete_post_meta()

Be careful when using this function to delete a specific key-value pair. Providing an empty string for $meta_value will skip the check, resulting in all keys being deleted. To avoid this, use a null value for $meta_value if you want to delete all entries with a specified $meta_key, regardless of the field value.

Examples

Deleting Metadata for a Specific Post

// Deleting the 'my_key' metadata for the post with ID 76
delete_post_meta(76, 'my_key');

Deleting Specific Metadata Value

// Deleting the 'my_key' metadata with the value 'Steve' for the post with ID 76
delete_post_meta(76, 'my_key', 'Steve');

Deleting Metadata Across All Posts

$allposts = get_posts('numberposts=-1&post_type=post&post_status=any');
foreach($allposts as $postinfo) {
    delete_post_meta($postinfo->ID, 'related_posts');
}

Deleting Metadata Except Specific Value

$allposts = get_posts('numberposts=-1&post_type=post&post_status=any');
foreach($allposts as $postinfo) {
    $inspiration = get_post_meta($postinfo->ID, 'post_inspiration');
    foreach($inspiration as $value) {
        if('Sherlock Holmes' !== $value) {
            delete_post_meta($postinfo->ID, 'post_inspiration', $value);
        }
    }
}

Deleting Metadata That References a Deleted Post

$allposts = get_posts('numberposts=-1&post_type=post&post_status=any');
foreach($allposts as $postinfo) {
    delete_post_meta($postinfo->ID, 'related_posts', '185');
}