Generate WP-CLI @alias for each site on multisite


LOCAL


For local aliases, it works best to define your path ahead of time in the config.yml. Then keep the variables pretty clean by only specifying the url to target the site. Sorting the output helps if you have a long list of sites since the default is by blog id (which we’re not using).

wp site list --field=url|sort|xargs -I 'SITE' sh -c 'ALIAS=$(cut -d"https://wordpress.stackexchange.com/" -f4 <<< SITE);if [ ! -z "$ALIAS" ];then echo -e "@$ALIAS:\n url: SITE";fi'

Result

path: /www/wordpress/

@site-a:
  url: http://domain.com/site-a/
@site-b:
  url: http://domain.com/site-b/

REMOTE


For remote aliases, it’s nicer to prefix them relative to the config.yml. So in this case, remote-. Also you can tack the WordPress path onto the ssh property.

HOME=$(wp eval "echo get_home_path();");wp site list --field=url|sort|xargs -I 'SITE' sh -c 'ALIAS=$(cut -d"https://wordpress.stackexchange.com/" -f4 <<< SITE);if [ ! -z "$ALIAS" ];then echo -e "@remote-$ALIAS:\n url: SITE\n [email protected]$HOME";fi'

Result:

@remote-site-a:
  url: http://domain.com/site-a/
  ssh: [email protected]/www/wordpress/
@remote-site-b:
  url: http://domain.com/site-b/
  ssh: [email protected]/www/wordpress/

LIST ALIASES


aliases=$(wp cli alias | cut -d':' -f1 | grep -e "^@" | cut -d':' -f2 | sort);

EXISTING ALIASES


aliases=$(wp cli alias | cut -d':' -f1 | grep -e "^@" | cut -d':' -f2 | sort);

search="@site-a"

if ! grep $search <<< "$aliases"; then echo "NOT FOUND"; fi

BASH REFERENCE


  • VAR=$(echo "stuff") – Capture output
  • HOME=$(wp eval "echo get_home_path();") – Run PHP and assign to var
  • wp site list --field=url | sort – Sorts the resulting site list
  • | xargs -I 'SITE' – For loop from pipe and use SITE as the value variable
  • | xargs -I % – Pick a symbol that makes sense
  • xargs -I 'ITEM' sh -c 'echo ITEM; echo "2nd";' – Run multiple bash commands
  • cut -d"https://wordpress.stackexchange.com/" -f4 <<< SITE – Split from variable
  • ALIAS=$(cut -d"https://wordpress.stackexchange.com/" -f4 <<< SITE) – Split URL on “https://wordpress.stackexchange.com/”, assign the 4th index to var
  • echo -e "\txyz\n\n" – Allow escaped characters
  • if [ ! -z "$ALIAS" ];then echo -e "";fi – Run on non-empty variable
  • wp cli alias | grep '^@' | grep ':$' – Multiple filters on results array
  • grep '^starts-with' – Line starts with value
  • grep 'ends-with$' – Line ends with value
  • sed "s,$url,,g" <<< "$site" – sed string replace with , separator
  • sed "s/find/replace/g" <<< "$value" – sed string replace with / separator (not good with urls)
  • wp site list --field=url | tail -n+2 – Skip first item
  • alias_name=$(sed "s,/,,g" <<< $(sed "s,$url,,g" <<< "$site")) – Multiple string replacements
  • for i in $(wp site list --field=url); do echo $i; done; – Loop through list

Leave a Comment