How to install and activate a plugin via an external PHP script

WP CLI

The easy way; use the WP CLI (also available as wp-cli.phar) to get a solid, maintainable solution for this requirement. More for this topic you will find at the command


WP API

If you will need a custom script is is necessary to load the WP API, via wp-load.php and look for the function activate_plugin($path_to_the_plugin).

Activation

As example what you need to get all requirements to activate a plugin see below

define( 'WP_ADMIN', TRUE );
define( 'WP_NETWORK_ADMIN', TRUE ); // Need for Multisite
define( 'WP_USER_ADMIN', TRUE );

require_once('../wp-load.php');
require_once( '../wp-admin/includes/admin.php' );
require_once( '../wp-admin/includes/plugin.php' );

activate_plugin( 'PATH_TO_THE_PLUGIN' );

Installation

The installation of a plugin is also possible via the API of WP, also code thats should helps a little bit to run in the right direction.

// Include required libs for installation
require_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );
require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
require_once( ABSPATH . 'wp-admin/includes/class-wp-ajax-upgrader-skin.php' );
require_once( ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php' );

// Get Plugin Info
$api = plugins_api( 'plugin_information',
    array(
        'slug' => $plugin,
        'fields' => array(
            'short_description' => false,
            'sections' => false,
            'requires' => false,
            'rating' => false,
            'ratings' => false,
            'downloaded' => false,
            'last_updated' => false,
            'added' => false,
            'tags' => false,
            'compatibility' => false,
            'homepage' => false,
            'donate_link' => false,
        ),
    )
);
$skin     = new WP_Ajax_Upgrader_Skin();
$upgrader = new Plugin_Upgrader( $skin );
$upgrader->install( $api->download_link );

A example that install and activate see you in this class.