Update WordPress Posts Post Meta with WP-CLI

May 16, 2018 - posted by Josh Smith

Recently I needed to update a big batch of posts’ post meta. I’m talking thousands of updates. Anything over about 20 updates involving the database and I immediately reach for WP-CLI.

Update Posts in Bulk

I built a plugin that pulls in results from a remote API. The API returns a set of 100 results per request. I only needed the first three and the option to pull in a custom about of data. If one of my WordPress posts needed to display 7 results then I would adjust that on a post by post basis. When I first built the plugin the default was a default setting of 3 API items to be returned. Later, my client asked me to change the default from 3 to 5. No big deal I’ll use the command line to update all the post meta that ACF (Advanced Custom Fields) created.

WP-CLI at Scale

The beauty of WP-CLI is that manages big amounts of data at once. It’s not really a speed thing as sometimes the commands take a really long time to run. It’s a volume thing. To get those big scaly actions to help you out you usually need to combine WP-CLI commands. I’ve talked about this at my local Meetup in Sacramento before. In a nutshell, you supply your main command with a list of IDs of posts you want to affect. The main command will use those IDs and execute on each of those posts. Let’s see it in action.

Update Post Meta with WP CLI

wp post meta update 2 my_post_meta_id true

I read the above command in very informal English like this, “Hey WordPress CLI, take the post meta and update it from post number 2. Find the meta key in the tables and change its value to true. It doesn’t matter what the value is now”.

stack exchange rubber duck avatar
Explain to the duck, it works!

It’s a silly process, but hey, explain it to the duck. That will work, but only for one post. We need to update many more than that and I don’t want to type more than I have to. Let’s expand and combine commands.

wp post meta update $(wp post list --format=ids) my_post_meta_id true

You could also put that in a Bash “for loop

for id in $(wp post list –format=ids); do wp post meta update $id dice_related_jobs_count 5; done


Now go work on something else while this works away. It could take hours.

© 2019 All Rights Reserved

Designed by Josh at Efficiency of Movement