Function and usage of delete_post_meta() in wordpress


Answers ( 1 )


    The delete_post_meta() function in WordPress is used to delete a metadata entry for a post. Here's a detailed explanation of its function, parameters, and usage:


    • Purpose: Deletes a post meta field for the given post ID.


    • This function allows you to remove metadata associated with a WordPress post.
    • You have the option to specify the deletion by:
      • Meta Key Only: If you only specify the meta key, all metadata entries with that key will be removed.
      • Meta Key and Meta Value: If you specify both the meta key and the meta value, only those entries that match both criteria will be deleted. This approach is useful for avoiding the deletion of duplicate metadata entries that have the same key but different values.


    1. $post_id (int, required): The ID of the post from which you want to delete the metadata.
    2. $meta_key (string, required): The name of the metadata field you want to delete.
    3. $meta_value (mixed, optional): The value of the metadata field you want to delete. This parameter is optional.
      • If provided, only those rows that match the specified value will be removed.
      • The value must be serializable if it's non-scalar (e.g., an array or object).
      • Default value is an empty string ''.

    Return Value:

    • Returns bool:
      • True on successful deletion.
      • False on failure (e.g., if no metadata with the specified key and value is found).

    Sample Usage:

    $post_id = 123; // Example post ID
    $meta_key = 'custom_meta_key'; // The meta key you want to delete
    // Delete all metadata for the specified key
    delete_post_meta($post_id, $meta_key);
    // Delete metadata for the specified key and value
    $meta_value = 'specific value'; // The meta value you want to match
    delete_post_meta($post_id, $meta_key, $meta_value);

    In these examples, the function is used to delete metadata from a post with ID $post_id. The first usage deletes all metadata entries with the key $meta_key, while the second one deletes only those entries where the key is $meta_key and the value is $meta_value.

Leave an answer