How to Delete All WordPress Posts that Have a Specific Custom Field

So, you want to delete any posts in a WordPress install that have a certain custom field, do you?

Maybe you’re allowing people to update posts from the front end, and depending on the fields they use, if a specific custom field is set we just go ahead and delete it. Or maybe you’re using custom fields as a way to manage content in some other way.

No matter, it’s fairly easy to do this. In functions.php, add the following:

// delete all posts that have something in a custom field
$args = array(
'posts_per_page' => -1,
'post_type' => 'post',
'meta_key' => 'YOURCUSTOMFIELD'
);
$the_query = new WP_Query( $args );
if ($the_query->have_posts()) {
while ( $the_query->have_posts() ) :
$the_query->the_post();
wp_delete_post(get_the_ID());
endwhile;
}
wp_reset_postdata();

Note! Change YOURCUSTOMFIELD to whatever the key of your custom field is.

You could also modify this to work if a certain custom field has a specific value, too, just add 'meta_value' => 'YOURVALUE' or any of the meta_query WordPress now has made available since version 3.1.

Up Next: Redesign Project: TalkingPointz.com