Using WordPress ‘delete_post_meta_by_key()’ PHP function

The delete_post_meta_by_key() WordPress PHP function deletes everything from post meta matching the given meta key.

Usage

To use the delete_post_meta_by_key() function, simply pass the post meta key as a string to the function. Here’s an example:

delete_post_meta_by_key('your_meta_key');

In this example, ‘your_meta_key’ is the meta key for the data you want to delete. This will delete all post meta data that matches ‘your_meta_key’.

Parameters

  • $post_meta_key (string) – The key to search for when deleting post meta data.

More information

See WordPress Developer Resources: delete_post_meta_by_key()

This function is used to delete all instances of a specific meta key from the database. Be careful when using it, as it can delete a large amount of data if not used properly.

Examples

Deleting a Specific Meta Key

In this example, we’re deleting all post meta data with the key ‘special_offer’:

delete_post_meta_by_key('special_offer');

This will remove any post meta data that has the key ‘special_offer’.

Deleting Multiple Meta Keys

If you want to delete multiple meta keys, you can do so by calling the function multiple times:

delete_post_meta_by_key('special_offer');
delete_post_meta_by_key('limited_time_offer');

This will delete all post meta data with the keys ‘special_offer’ and ‘limited_time_offer’.

Deleting Meta Keys within a Function

You can also use this function within another function to perform a bulk delete:

function clear_promotional_meta() {
  delete_post_meta_by_key('special_offer');
  delete_post_meta_by_key('limited_time_offer');
}

clear_promotional_meta();

In this example, the clear_promotional_meta() function will delete all post meta data with the keys ‘special_offer’ and ‘limited_time_offer’.

Using Meta Keys from Variables

You can also delete meta keys from variables:

$meta_key = 'special_offer';

delete_post_meta_by_key($meta_key);

In this example, the ‘special_offer’ meta key is stored in the $meta_key variable.

Deleting Meta Keys in a Loop

If you have an array of meta keys, you can loop through them and delete each one:

$meta_keys = ['special_offer', 'limited_time_offer', 'sale'];

foreach ($meta_keys as $key) {
  delete_post_meta_by_key($key);
}

This will delete all post meta data with the keys ‘special_offer’, ‘limited_time_offer’, and ‘sale’.