Install plugins with AJAX using the built in WordPress AJAX API
Whether you’re new to WordPress development or an experienced professional, this guide will show you how to install plugins via AJAX using wp_ajax_install_plugin()
. We’ll cover everything from the basics to advanced tips for integrating this functionality into your custom admin pages or plugin dashboards.
- Introduction
- How
wp_ajax_install_plugin()
Works - Step 1: Enqueue Necessary Scripts
- Step 2: Create the AJAX Call in JavaScript
- Step 3: Handle the AJAX Request in PHP
- Step 4: Test the Plugin Installation
- Advanced Considerations (Optional)
Introduction
WordPress offers a powerful AJAX API that simplifies creating dynamic and interactive features in both the admin and front-end interfaces. One of its lesser-known but highly useful capabilities is the built-in function wp_ajax_install_plugin()
, which lets you install plugins without leaving the current page.
This feature is excellent for:
- Custom plugin managers that install recommended plugins with one click.
- Smooth onboarding where required plugins are automatically installed for new users.
- User-friendly admin enhancements enabling administrators to manage multiple plugins quickly.
By the end of this tutorial, you’ll be able to seamlessly integrate plugin installation features into your own projects.
How wp_ajax_install_plugin()
Works
wp_ajax_install_plugin()
is a core WordPress AJAX action that routes requests to install plugins through the standard WordPress AJAX handler (wp_ajax_
+ your action name). In practice, you’ll:
- Enqueue scripts that enable WordPress updates and plugin installs.
- Trigger an AJAX request from your JavaScript code.
- Handle the request in PHP by verifying permissions, calling WordPress’s internal plugin installer, and returning success or error messages.
Step 1: Enqueue Necessary Scripts
Before making an AJAX request, you need to load the WordPress scripts that handle plugin installations and updates. Add the following function to your plugin or theme’s functions.php
(or a custom admin file):
function enqueue_plugin_install_script() {
// Load WordPress's built-in plugin installation & update scripts
wp_enqueue_script('plugin-install');
wp_enqueue_script('updates');
// Make the admin-ajax URL available to our JavaScript
wp_localize_script('plugin-install', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('admin_enqueue_scripts', 'enqueue_plugin_install_script');
Why this matters:
plugin-install
andupdates
provide the JavaScript functions and hooks that power plugin downloads and updates in core WordPress.wp_localize_script
ensures our script knows where to send the AJAX request (admin-ajax.php
).
Step 2: Create the AJAX Call in JavaScript
Next, you’ll write a JavaScript function that triggers the plugin installation process. You can place this script in your custom admin page or a dedicated JS file.
jQuery(document).ready(function ($) {
$('.install-plugin-button').on('click', function (e) {
e.preventDefault();
var pluginSlug = $(this).data('slug'); // Retrieve plugin slug from button
if (!pluginSlug) {
alert("Plugin slug is missing.");
return;
}
// Prepare the data for our AJAX request
var data = {
action: 'install_plugin', // The AJAX action name
slug: pluginSlug, // The plugin slug
_ajax_nonce: wp.updates.ajaxNonce // The WordPress-generated nonce for security
};
// Send the AJAX request
$.post(ajaxurl, data, function (response) {
if (response.success) {
alert("Plugin installed successfully!");
} else {
// Display an error message returned by the server
alert("Plugin installation failed: " + (response.data || "Unknown error"));
}
});
});
});
Add a button in your admin HTML or PHP file:
<button class="install-plugin-button" data-slug="hello-dolly">Install "Hello Dolly"</button>
Key points:
data-slug
must match the plugin’s slug (usually found in the URL on wordpress.org).wp.updates.ajaxNonce
is a built-in WordPress nonce used for update-related actions (ensures only authorized users can proceed).
Step 3: Handle the AJAX Request in PHP
Now, create a handler for the install_plugin
AJAX action. Add this to your functions.php
or a custom plugin file:
function handle_ajax_install_plugin() {
// 1. Check user capabilities
if (!current_user_can('install_plugins')) {
wp_send_json_error(['message' => 'You do not have permission to install plugins.']);
}
// 2. Verify nonce (important for security)
check_ajax_referer('updates');
// 3. Validate plugin slug
if (empty($_POST['slug'])) {
wp_send_json_error(['message' => 'Plugin slug is required.']);
}
// 4. Include required WordPress files for installation
include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
// 5. Retrieve plugin information
$plugin_slug = sanitize_text_field($_POST['slug']);
$api = plugins_api('plugin_information', ['slug' => $plugin_slug]);
if (is_wp_error($api)) {
wp_send_json_error(['message' => 'Could not retrieve plugin information.']);
}
// 6. Perform the installation
$upgrader = new Plugin_Upgrader(new Automatic_Upgrader_Skin());
$result = $upgrader->install($api->download_link);
if (is_wp_error($result)) {
wp_send_json_error(['message' => $result->get_error_message()]);
}
// 7. Return success response
wp_send_json_success(['message' => 'Plugin installed successfully.']);
}
add_action('wp_ajax_install_plugin', 'handle_ajax_install_plugin');
Important details:
current_user_can('install_plugins')
ensures only users with correct privileges can install plugins (usually Administrators).check_ajax_referer('updates')
confirms the request is legitimate and prevents CSRF attacks.wp_send_json_success()
andwp_send_json_error()
provide standardized JSON responses for your JavaScript callback.
Step 4: Test the Plugin Installation
- Log in as an administrator (only admins can install plugins by default).
- Go to your custom admin page (or wherever you added the button).
- Click your Install Plugin button.
- Verify that the plugin is installed (check Plugins > Installed Plugins).
If everything is set up correctly, you should see “Plugin installed successfully!”.
Troubleshooting Tips:
- If you see permission errors, make sure you’re logged in as an admin.
- If a nonce error appears, confirm you have
wp.updates.ajaxNonce
set and thatplugin-install
andupdates
scripts are properly enqueued.
Advanced Considerations (Optional)
Activate the Plugin After Installation
To activate the plugin automatically, you can callactivate_plugin()
after successful installation. Example:// After $upgrader->install($api->download_link);
$activate = activate_plugin($upgrader->plugin_info());
if (is_wp_error($activate)) {
wp_send_json_error(['message' => $activate->get_error_message()]);
}
wp_send_json_success(['message' => 'Plugin installed and activated successfully.']);Custom UI Feedback
- Display loading spinners or progress bars while the plugin is installing.
- Update buttons (e.g., disabling them during installation).
- Show success/error notifications using JavaScript popups or WordPress admin notices.
Error Logging
For debugging, log errors witherror_log()
or use plugins like Query Monitor to see what’s happening under the hood.Security Best Practices
- Always check user capabilities.
- Validate all inputs.
- Use nonces and verify them.
- Restrict plugin installation to trusted sources (like WordPress.org).
Congratulations! You now know how to use wp_ajax_install_plugin()
to install plugins via AJAX. This technique opens the door to user-friendly admin experiences, guided onboarding flows, and custom plugin managers that streamline WordPress administration.
Next Steps:
- Add more robust error handling and UI feedback.
- Integrate automatic plugin activation.
- Extend your admin page with recommended or required plugins lists.