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.
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.
3 Answers
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');
?>