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

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

  • 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. – IXN Dec 14 '15 at 21:02
  • The action hook I provided with it. It's init. So use it on functions.php or your plugins Main file – Kvvaradha Dec 15 '15 at 0:50

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.