Step 1 – Export the current custom field values to a CSV.
I wrote a quick shortcode to dump all of the current settings for all posts to the screen. I then saved that to a CSV and imported it into Excel where I could manipulate the strings.
The resulting output looked like this:
Step 2 – Build the commands in Excel.
Now that you have a list of all posts you want to operate on and their values, we can use Excel to build formulae that output the wp cli commands that we want to run on the server.
I needed to update two taxonomies, but I’ll only show one here for the sake of brevity.
For this operation, I want to take the value stored in the year field and make it tags under the year-presentation taxonomy. The formula I used in Excel to build my commands was:
="wp post term set "&A2&" year-presentation "&B2
And that gave me a column which contained all of the commands I needed to run.
|624||2011||Chicago||wp post term set 624 year-presentation 2011|
|638||2011||Paris||wp post term set 638 year-presentation 2011|
|644||2011||Paris||wp post term set 644 year-presentation 2011|
|665||2011||Paris||wp post term set 665 year-presentation 2011|
One big word of caution – some city names had two words in them, like “Fort Worth” and “San Diego.” I didn’t take that into account before running the following command:
wp post term set 1403 city-presentation fort worth
That created two new tags, fort and worth, for each post that had Fort Worth selected as the city. I needed to pass fort-worth as the tag instead, like this:
wp post term set 1403 city-presentation fort-worth
Step 3 – Run the commands on the server.
Just copy and paste those commands into your SSH console and let wp cli do all the work!
This was the first time that I used wp cli to do any heavy lifting on a site, and I can safely say that it allowed me to do a ton of work in a fraction of the time it would have taken to do by hand, and with far fewer human errors. By building the list of commands in Excel I was able to keep track of all of the operations and even recover from the accidental double tag issue with two-word city names.
I hope this guide helps you use wp cli to automate some process for your site.
PS – The wp cli documentation isn’t terrible, but it’s lacking command line examples that would have really helped a beginner like me out. Perhaps one day I’ll contribute to that site, too.