Generating a WordPress plugin activation link url

As I might need it again I’ve put together a gist for a WordPress function that will generate a plugin activation url like the ones WordPress will generate in the plugins administration screen

Activate link
Activate link

The function will require a string input like my-plugin/my-plugin.php which can be hard-coded knowing a specific plugin folder and main plugin file information or using another function that will check for an installed plugin using its title.

/**
 * Generate an activation URL for a plugin like the ones found in WordPress plugin administration screen.
 *
 * @param  string $plugin A plugin-folder/plugin-main-file.php path (e.g. "my-plugin/my-plugin.php")
 *
 * @return string         The plugin activation url
 */
function generatePluginActivationLinkUrl($plugin)
{
    // the plugin might be located in the plugin folder directly

    if (strpos($plugin, '/')) {
        $plugin = str_replace('/', '%2F', $plugin);
    }

    $activateUrl = sprintf(admin_url('plugins.php?action=activate&plugin=%s&plugin_status=all&paged=1&s'), $plugin);

    // change the plugin request to the plugin to pass the nonce check
    $_REQUEST['plugin'] = $plugin;
    $activateUrl = wp_nonce_url($activateUrl, 'activate-plugin_' . $plugin);

    return $activateUrl;
}

2 thoughts on “Generating a WordPress plugin activation link url

  1. Thank you for sharing your knowledge on this. Are you able to provide an example of the precise code used to create an activation link within an html/php file? I know the path to the plugin, just not where to place that path within your solution.

    1. The function requires the $plugin variable to be a path relative to the plugins folder in the folder/main-plugin-file.php format.
      This means that a call would be $activation_link = generatePluginActivationLinkUrl('my-plugin/my-plugin.php'); and use that variable in an anchor tag, hidden input or whatever.

I appreciate your input