Say you have 50 posts in your WordPress and you want to update to a new template? You could update them in the admin panel, but that would mean a lot of clicking around.
Luckily there’s an easy one liner that you can use to update page templates in bulk. You’ll need to have WP CLI installed for this to work. This one liner comes from this snippet by Mike Little and has been modified to work for template updates
How to update page templates multiple posts at a time with WP CLI
This is the one liner you can use to update ALL posts to use a new template.
for id in $(wp post list --post_type=post --fields=ID --format=ids); do wp post meta update $id _wp_page_template 'your-template-name-goes-here'; done
REMEMBER to change the template name (‘your-template-name-goes-here’) to match your own. Other than that it’s ready to go. I’d also do a trial run with the code below before you run through that because it updates all your posts at one go.
How to update page templates from a CSV list in WordPress
A slight tweak to the bulk meta update allows you to use a CSV list to target specific pages.
for id in $(wp post list --post_type=post --post__in=7482,7434,5470 --fields=ID --format=ids); do wp post meta update $id _wp_page_template 'your-template-name-goes-here'; done
After the post_in= section is where you can copy and paste the comma separated list you have from somewhere else. Remember to change the numbers to post IDs in your own system.
That’s it! Have fun.