Delete All Post Meta Except Thumbnail In WordPress Posts
- Article
- Comment (2)
Delete All Post Meta Except Thumbnail In WordPress Posts.Removing all post metas to all posts is not like an ordinary querying functions. so be-careful and think before you start doing that , it may delete your any other important post meta. Let’s see the function which helps do it. Lets hook an init action with our function.
add_action('init','kv_delete_all_meta_except_featuredimg');
and lets write the function and query all posts with post types.
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 ); }
Now, we have to loop and get each posts, once you grab each post, than you can get all the post meta’s, Here we will omit the necessary things . I am just omitting the thumbnail and attachment’s attachment data’s.
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); } } } }
Here is your final code.
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');
Thanks for the code and your answer in stackexchange.
As I commented there, i wonder if we should add this into functions.php or add it as a plugin run it once and remove.
Replied you there.