0

I'm cleaning up a theme and one of Custom Post Types has some odd, long gone custom fields.

I want to delete them, unfortunately delete_post_meta() takes post->ID for an argument, while I want to perform this action on all the posts not only one.

How should I do that? Using a loop? Let's say the CPT is called "custom_photos" and every single post there has these custom fields.

1 Answer 1

2

The Core lacks a function for that kind of bulk delete, so far as I know. The safest thing to do is to Loop over the posts in your CPT and delete the fields.

$del = array(
  'list',
  'of',
  'keys',
  'to',
  'delete'
);

$args = array(
  'post_type' => 'book',
  'posts_per_page' => -1,
  'ignore_sticky_posts' => true,
  'fields' => 'ids',
  'no_found_rows' => true
);
$q = new WP_Query($args);

if (!empty($q->posts)) {
  foreach ($q->posts as $pid) {
    foreach ($del as $d) {
      delete_post_meta($pid,$d);
    }
  }
}

Unless you have an truly impressive number of posts in that CPT or a very overloaded server, that should work fine for the occasional cleanup.

If these fields are specific to your one post type and you aren't worried about losing data that might be associated with other post types, you can do the same with SQL.

$del = array(
  'list',
  'of',
  'keys',
  'to',
  'delete'
);

$sql = "DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ('".implode("','",$del)."')";
$wpdb->query($sql);

That is of course somewhat less "future proof" as database structure could change, though in this case I doubt it.

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.