I've got a lot of post meta keys that I no longer use, and I'm trying to work out how to delete them so they no longer show in the custom fields list in the admin panel.

enter image description here

This code will delete the post meta values:

function hp_batch_delete_post_meta(){

    // get array of all post ids
    $post_ids = get_posts( array(
        'numberposts'   => -1,
        'fields'        => 'ids',
        'post_type'     => array('ad_upload','post', 'page'),
        'post_status'   => array('publish', 'auto-draft', 'trash', 'pending', 'draft'),
    ) );

    // remove post meta for each post
    foreach( $post_ids as $post_id ) { 
        delete_post_meta($post_id, 'my_postmeta_key_1');
        delete_post_meta($post_id, 'my_postmeta_key_2');
        delete_post_meta($post_id, 'my_postmeta_key_3');
add_action('init', 'hp_batch_delete_post_meta');

But I would like to completely remove the meta keys too so they don't show in that admin list.

Any help appreciated.

  • Those meta keys might still exist in the database. You could try to run the following query and see if there are any orphaned meta keys SELECT * FROM {$wpdb->postmeta} as pm LEFT JOIN {$wpdb->posts} as p ON pm.post_id = p.ID WHERE p.ID IS NULL – czerspalace Nov 18 '16 at 21:06

I found this from just a Google search (Source)

You have to change met value keys as you want. However, it is highly recommend to take a DB backup before running this code.

function delete_useless_post_meta() {
   global $wpdb;
   $table = $wpdb->prefix.'postmeta';
   $wpdb->delete ($table, array('meta_key' => '_edit_last'));
   $wpdb->delete ($table, array('meta_key' => '_edit_lock'));
   $wpdb->delete ($table, array('meta_key' => '_wp_old_slug')); }
| improve this answer | |

If you want to delete keys with a wildcard criteria of some sort (as I did) then you can do this directly in SQL.

DELETE FROM `wp_postmeta` WHERE `meta_key` LIKE 'weather_%'
| improve this answer | |

This is quite an old post, but there is a much better way to do this.

WordPress core has a function where you can delete all meta data by a key.

delete_metadata( string $meta_type, int $object_id, string $meta_key, mixed $meta_value = '', bool $delete_all = false );


Use it this way:

delete_metadata( 'post', 0, 'meta_key_to_delete', false, true );

This would apply to all post types, published status, etc. So to delete the examples meta keys as above:

$deletable = array( 'my_postmeta_key_1', 'my_postmeta_key_2', 'my_postmeta_key_3' );
foreach( $deleteable as $to_delete ) {
  delete_metadata( 'post', 0, $to_delete, false, true );
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.