Quantcast
Viewing latest article 2
Browse Latest Browse All 27049

Limit installable themes and plugins on a WordPress multisite

I need (for educational purposes) to limit which themes and plugins are installable -globally, not site by site- on the individual wordpress websites created in a multisite installation. I know I can avoid that my students install new themes and plugins altogether, but this is not what I want. I want that they can test how to install new plugins and themes, but not to leave them free to install whatever plugin or theme.

I got this code from openai, with directions to save it as restrictions-installation.phpin wp-content/mu-plugins/:

<?php
/*
Plugin Name: Plugin and Theme Installation Restrictions
Description: Restricts plugin and theme installation to only approved ones in a multisite network.
Version: 1.0
Author: ChatGPT
*/

// Whitelisted plugins (slug, e.g., contact-form-7, akismet)
define('ALLOWED_PLUGINS', [
'akismet',
'classic-editor',
'contact-form-7'
]);

// Whitelisted themes (slug, e.g., twentytwentyfour, astra)
define('ALLOWED_THEMES', [
'twentytwentyfour',
'astra'
]);

// Block unauthorized plugins before installation
add_filter('upgrader_pre_install', 'restrict_plugin_installation', 10, 2);
function restrict_plugin_installation($response, $hook_extra) {
if (isset($hook_extra['plugin'])) {
$slug = dirname($hook_extra['plugin']);
if (!in_array($slug, ALLOWED_PLUGINS)) {
return new WP_Error('plugin_not_allowed', __('This plugin is not allowed on the multisite network.'));
}
}
return $response;
}

// Block unauthorized themes from being installed via the official directory
add_filter('themes_api', 'restrict_theme_installation', 10, 3);
function restrict_theme_installation($result, $action, $args) {
if (isset($args->slug) && !in_array($args->slug, ALLOWED_THEMES)) {
return new WP_Error('theme_not_allowed', __('This theme is not allowed on the multisite network.'));
}
return $result;
}

// Prevent activation of unauthorized themes (e.g., if uploaded manually)
add_action('switch_theme', 'block_unauthorized_theme_activation');
function block_unauthorized_theme_activation($new_name) {
if (!in_array($new_name, ALLOWED_THEMES)) {
wp_die(__('The selected theme is not allowed on the multisite network.'));
}
}

As I’m not expert of WordPress code, and before making my multisite crash, do you think this could work? Thanks in advance


Viewing latest article 2
Browse Latest Browse All 27049

Trending Articles