WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/delete post meta

Description

This function deletes all custom fields with the specified key, or key and value, from the specified post. See also update_post_meta(), get_post_meta() and add_post_meta().

Usage

 <?php delete_post_meta($post_id$meta_key$meta_value); ?> 

Parameters

$post_id
(integer) (required) The ID of the post from which you will delete a field.
Default: None
$meta_key
(string) (required) The key of the field you will delete.
Default: None
$meta_value
(mixed) (optional) The value of the field you will delete. This is used to differentiate between several fields with the same key. If left blank, all fields with the given key will be deleted.
Default: Empty

Return values

(boolean) 
False for failure. True for success.

Examples

Default Usage

<?php delete_post_meta(76, 'my_key', 'Steve'); ?>

Other Examples

Let's assume we had a plugin that added some meta values to posts, but now when we are uninstalling the plugin, we want to delete all the post meta keys that the plugin added. Assuming the plugin added the keys related_posts and post_inspiration.

To delete all the keys use delete_post_meta_by_key( $post_meta_key ). This would be added to the "uninstall" function:

<?php delete_post_meta_by_key( 'related_posts' ); ?>

Or, if you wanted to delete all the keys except where post_inspiration was "Sherlock Holmes":

<?php
  $allposts = get_posts( 'numberposts=-1&post_type=post&post_status=any' );

  foreach( $allposts as $postinfo ) {
    delete_post_meta( $postinfo->ID, 'related_posts' );
    $inspiration = get_post_meta( $postinfo->ID, 'post_inspiration' );
    foreach( $inspiration as $value ) {
      if( 'Sherlock Holmes' !== $value )
        delete_post_meta( $postinfo->ID, 'post_inspiration', $value );
    }
  }
?>

Or maybe post number 185 was just deleted, and you want to remove all related_posts keys that reference it:

<?php
  $allposts = get_posts( 'numberposts=-1&post_type=post&post_status=any' );

  foreach( $allposts as $postinfo ) {
    delete_post_meta( $postinfo->ID, 'related_posts', '185' );
  }
?>

For a more detailed example, go to the post_meta Functions Examples page.

Note: Unlike update_post_meta(), This function will delete all fields that match the criteria.

Source File

delete_post_meta() is located in wp-includes/post.php

Change Log

Since 1.5.0

Related

Custom Fields: the_meta(), get_post_meta(), add_post_meta(), update_post_meta(), delete_post_meta(), get_post_custom(), get_post_custom_values(), get_post_custom_keys() (See Also: post_meta Function Examples)

See also index of Function Reference and index of Template Tags.