Skip to content

Instantly share code, notes, and snippets.

@ajgagnon
Created June 9, 2021 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajgagnon/60a765201210db2fb9a43d77efcccd9b to your computer and use it in GitHub Desktop.
Save ajgagnon/60a765201210db2fb9a43d77efcccd9b to your computer and use it in GitHub Desktop.
Automatically Install Plugin From Repo Example
<?php
namespace PrestoPlayer\Pro\Services;
/**
* Install core plugin if not installed/activated
*/
class CoreInstaller
{
private $slug = 'presto-player';
public $plugin = 'presto-player/presto-player.php';
/**
* Maybe install the core plugin
*
* @return void
*/
public function maybeInstallCore()
{
if (is_plugin_active($this->plugin)) {
return;
}
if (!current_user_can('install_plugins')) {
return;
}
$this->installPlugin();
}
/**
* Install the plugin from the source
*/
public function installPlugin()
{
include_once ABSPATH . 'wp-admin/includes/file.php';
include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
// if exists and not activated, activate it
if (file_exists(WP_PLUGIN_DIR . '/' . $this->plugin)) {
return activate_plugin($this->plugin);
}
// seems like the plugin doesn't exists. Download and activate it
$upgrader = new \Plugin_Upgrader(new \WP_Ajax_Upgrader_Skin());
$api = plugins_api('plugin_information', array('slug' => $this->slug, 'fields' => array('sections' => false)));
$result = $upgrader->install($api->download_link);
if (is_wp_error($result)) {
return $result;
}
return activate_plugin($this->plugin);
}
}
<?php
/**
* The code that runs during plugin activation
*/
register_activation_hook(__FILE__, function () {
if (!class_exists('\PrestoPlayer\Plugin')) {
(new \PrestoPlayer\Pro\Services\CoreInstaller)->maybeInstallCore();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment