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

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;
}

Source: https://www.theaveragedev.com/generating-a-wordpress-plugin-activation-link-url/