get_error_message();
} else {
$message = $result;
}
}
}
?>
Local Plugin Downloader
Enter a WordPress.org plugin slug (example: contact-form-7) to download and install it.
$slug,
‘fields’ => [‘downloadlink’ => true],
]);
if (is_wp_error($api)) return $api;
if (empty($api->download_link)) {
return new WP_Error(‘no_download’, ‘No download link found for that slug.’);
}
// 2) Ensure filesystem credentials are ready (local usually “direct”)
$url = admin_url(‘tools.php?page=local-plugin-downloader’);
$creds = request_filesystem_credentials($url);
if ($creds === false) {
return new WP_Error(‘fs_creds’, ‘Filesystem credentials required. Please try again.’);
}
if (!WP_Filesystem($creds)) {
return new WP_Error(‘fs_init’, ‘Could not initialize filesystem.’);
}
// 3) Install via upgrader
$skin = new Automatic_Upgrader_Skin();
$upgrader = new Plugin_Upgrader($skin);
$installed = $upgrader->install($api->download_link);
if (!$installed) {
$msg = $skin->get_errors() ? $skin->get_errors()->get_error_message() : ‘Install failed.’;
return new WP_Error(‘install_failed’, $msg);
}
// 4) Find the installed plugin file (e.g. folder/plugin.php)
$plugin_file = lpd_find_plugin_main_file($slug);
$doneMsg = ‘Installed successfully.’;
// 5) Optional activate
if ($activate && $plugin_file) {
$act = activate_plugin($plugin_file);
if (is_wp_error($act)) return $act;
$doneMsg = ‘Installed and activated successfully.’;
}
return $doneMsg;
}
function lpd_find_plugin_main_file(string $slug) {
// Search installed plugins for folder matching slug
$plugins = get_plugins();
foreach ($plugins as $file => $data) {
// $file looks like “plugin-folder/plugin.php”
if (str_starts_with($file, $slug . ‘/’)) {
return $file;
}
}
// If slug differs from folder name, fallback to first plugin in the newest folder is harder;
// return null and just report install success.
return null;
}