1

My aim is to clear up my database entries. I did a migration from blogger which added many useless post_meta. I found a plugin (db reset) that has the option to reset/delete all post meta. However if I delete all post meta I lose my featured image (post thumbnails) settings.

I'm not very familiar with phpmyadmin. How can I delete all post meta except the featured image?

1 Answer 1

2

The below code will help you to remove all the post meta's except the thumbnail of a post.

 function kv_delete_all_meta_except_featuredimg(){ $args = array( 'posts_per_page' => -1, 'post_status' => 'any', 'post_type' => array('attachment', 'page','post')); $articles= get_posts( $args ); foreach($articles as $article){ if($article->post_type == 'attachment'){ $myvals = get_post_meta($article->ID); foreach($myvals as $key=>$val) { if($key == '_wp_attached_file' || $key == '_wp_attachment_metadata'){} else { delete_post_meta($article->ID, $key); } } }else { $myvals = get_post_meta($article->ID); foreach($myvals as $key=>$val) { if($key != '_thumbnail_id' ){ delete_post_meta($article->ID, $key); } } } } } add_action('init','kv_delete_all_meta_except_featuredimg'); 

Note :*** Remember This will remove all the post meta keys and its associated values. So take a backup before proceeding with it. Just add this function on your theme functions.php. Here i assumed you may have only these post types attachment, post, page. if you have any extra post types, add with it.

You can read here for more details I wrote an article about it. Kvcodes

2
  • I have not tested this yet, but it would make a great plugin. I wonder if this should be a "functions.php" function or an apply once and remove plugin. Commented Dec 14, 2015 at 21:02
  • The action hook I provided with it. It's init. So use it on functions.php or your plugins Main file Commented Dec 15, 2015 at 0:50

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.