How to update an ‘array’ option using wp-cli [duplicate]

Thanks to a tip from milo in the comments above, I looked at this similar question.

There is an answer provided by Laurent which basically gets the option using wp-cli, pipes it to an inline php program, makes the adjustments and then pipes it back to wp-cli. I took that idea and generalized it somewhat by creating a file sibling to my cloning script: update-array-option.sh.

#!/bin/bash

option_name=$1
option_key=$2
option_value=$3

wp option get ${option_name} --format=json | php -r "
\$option = json_decode( fgets(STDIN) );
\$option->${option_key} = \"${option_value}\";
print json_encode(\$option);
" | wp option set ${option_name} --format=json

Usage then becomes:

./update-array-option.sh <option-name> <option-key> <value>

Specifically for this question:

./update-array-option.sh woocommerce_stripe_settings testmode yes

Obviously this is quick and dirty and won’t handle all of the edge cases. It looks and feels gross to be mixing bash / php like this, and as with all things relating to strings in bash, YMMV.

Leave a Comment