Batch Install WordPress Plugins using WP-CLI Bash Script

WP-CLI is an indispensable tool for WordPress power users. Hosts, developers, system administrators probably use WP-CLI every day. It can help you automate tedious tasks like bulk plugin updates for multiple sites. I saw a post on the facebook group Advanced WordPress of a gist that installed a list of plugins in one list. This is my adaptation of those commands for you to integrate into your provisioning toolbox.

Batch Install WordPress Plugins using WP-CLI Bash Script

Install WP-CLI and make the user own it with executable permissions.

sudo wget -q https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar -O /usr/bin/wp
sudo chown user /usr/bin/wp
sudo chmod 755 /usr/bin/wp

Here is the simplest way to batch install WordPress plugins on a fresh installation, server or container.

We define an array that is full of the plugins we want to install on new machines and then WP-CLI installs and activates them all

You should change your WPPATH to the path of your WordPress installation.

#!/usr/bin/env bash
#WordPress Batch Plugin Installer WP-CLI
#Author https://guides.wp-bullet.com

#define array of plugin slugs to install
WPPLUGINS=( wordpress-seo ewww-image-optimizer better-wp-security aceide )

#specify path to WordPress installation
WPPATH=/var/www/guides.wp-bullet.com

wp plugin install ${WPPLUGINS[@]} --activate --path=$WPPATH --allow-root

#Fix permissions in case you ran as root
sudo chown -R www-data:www-data $WPPATH
sudo find $WPPATH -type f -exec chmod 644 {} +
sudo find $WPPATH -type d -exec chmod 755 {} +

Here is a smarter version that will check if the WordPress installation already has the plugin installed.

This would be useful if you are managing many existing WordPress installations and want to reprovision them all.

#!/usr/bin/env bash

#WordPress Batch Plugin Installer WP-CLI
#Author https://guides.wp-bullet.com

#define array of plugin slugs to install
WPPLUGINS=( wordpress-seo ewww-image-optimizer better-wp-security )

#specify path to WordPress installation
WPPATH=/var/www/guides.wp-bullet.com

#loop through array, install and activate the plugin, ${WPPLUGINS[@]}
for WPPLUGIN in "${WPPLUGINS[@]}"; do
#check if plugin is installed, sets exit status to 1 if not found
    wp plugin is-installed $WPPLUGIN --path=$WPPATH --allow-root

#install plugin if not present based on exit code value
    if [ $? -eq 1 ]; then
        wp plugin install $WPPLUGIN --activate --path=$WPPATH --allow-root
    fi
done

#Fix permissions in case you ran as root
sudo chown -R www-data:www-data $WPPATH
sudo find $WPPATH -type f -exec chmod 644 {} +
sudo find $WPPATH -type d -exec chmod 755 {} +

Hopefully these help make your WordPress automation life easier :).

Sources

WP-CLI Plugin Command
WP-CLI Plugin is-installed Command
Displaying Entire Array Methods
Using exit codes in Bash