Skip to content

Bulk Update Post Meta Data

Bulk Update Post Meta Data Wordpress

Bulk Updating WordPress Post Meta Data

There are occasions when you’ll come across the need to bulk update your post meta data in WordPress.  We recently needed this to update a specific post type to use a new template.  Keep in mind this will only benefit you if you need a blanket fix to update all posts with a new meta value.  

Don’t let this task scare you off by thinking it requires some complex SQL query.  It doesn’t! Rest assured the below snippet can be tailored to solve your bulk update needs.  

The function below adds an action to “init” meaning it will load immediately – so don’t forget to remove it when you’re done!  Basically this function will loop through all posts of a specific post type, and update the post meta data to match a key with a new value.  Be careful and make a DB backup prior to using this code as it will update ALL posts that match the post type specificed in the arguments.

Add this to functions.php

add_action('init', 'bulk_update_post_meta_data');
function bulk_update_post_meta_data() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'POSTTYPEHERE',
'suppress_filters' => true
);

$posts_array = get_posts( $args );

foreach($posts_array as $post_array) {
update_post_meta($post_array->ID, 'POSTMETAKEY', 'NEWVALUE');
}
}

The yellow highlighted areas will need to be changed to meet your specific needs.

Customize for your needs

POSTTYPEHERE This is the post type you are targeting (i.e. POST)

POSTMETAKEY The post meta key you’d like to change (i.e. a page template)

NEWVALUE The new value you’d like to apply to ALL posts that meet the post type criteria.

Load site once, then remove

Load your site URL (frontend) once – then remove or comment this code out thereafter.  No need to keep this function active as it will continue to run on every page load.  You can also customize this further to load on a specific page if you’d like.

Did it work for you? Let us know if you’re having trouble in the comments and we’ll pitch in!

Comments