wp cli – bulk post meta update

When the time comes and you need to update meta data for zillion of your posts at once dandy script is handy.

One think is to write a php script with a simple query but if you have zillion posts you’ll hit the php time execution or other limits, and stay frustrated.

Lets forget about plugins and such and lets look on the WP CLI tool. Yes you need to have SSH access and yes you need to WP CLI installed.. but that is obvious and common scenario, or at least in cases when you have decent hosting that allows you to have all that tools available.. if not.. it’s time to question you hosting provider why they are so obsolete.. another story.

As the post meta query might be expensive, the WP CLI won’t let you update multiple meta at once as you might think.. like

wp post meta update $(wp post list –post_type=’locations’ –format=ids) print_textarea ” –dry-run

nope, that des not work, you have to do it one by one, like so

for id in $(wp post list –post_type=’locations’ –format=ids); do wp post meta get $id print_textarea; done

Success: Updated custom field ‘print_textarea’.
Success: Value passed for custom field ‘print_textarea’ is unchanged.
Success: Value passed for custom field ‘print_textarea’ is unchanged.
Success: Value passed for custom field ‘print_textarea’ is unchanged.
….

and that is it. Isn’t it easy?

bit of explanation:
for” is obvious loop. $(wp post … ) query the db as like you would with WP_QUERY call, all obvious variables are there.. that will give you all posts of given type, concretely their ids.. then you can do your tricks on the meta you choose.

Run theĀ –dry-run, and backup the database before you commit.