3

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
2

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.

<?php
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')); }
add_action('wp_logout','delete_useless_post_meta');
?>
1

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_%'

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.