What are WordPress MU-Plugins? (ok)

The Must-Use Plugins Directory

A mu-plugin is similar to a classic plugin, except that it is not stored in the plugins directory of the wp-content folder, but rather in the mu-plugins directory, of the same folder. If you have never used mu-plugins before, this directory should not exist, but you can create it without any problem.

Note that the directory where you will store your mu-plugins is /wp-content/mu-plugins, but you can change this by defining two constants in the wp-config.php file: WPMU_PLUGIN_DIR and WPMU_PLUGIN_URL.

define('WPMU_PLUGIN_DIR', '/full/path/to/the/new/directory');
define('WPMU_PLUGIN_URL', 'http://URL/to/the/new/directory');

Be careful: if you define these two constants, WordPress won’t redefine them, so if the path is not valid, mu-plugins won’t be loaded. Moreover, in the wp-config.php file, you must define these constants before the line where WordPress includes the wp-settings.php file, that means you won’t be able to use some useful constants like WP_CONTENT_DIR for example.

Our First Must-Use Plugin

C:\xampp\htdocs\wordpress4\wp-content\mu-plugins\hello-world.php

<?php  
  function displayHelloWorld() {
    echo '<p style="position: fixed;bottom: 0;right: 0;padding: 10px;background-color: #0096FF;color: #FFFFFF;width: 100%;text-align: center;">Hello World!</p>';
  }
?>

C:\xampp\htdocs\wordpress4\wp-content\themes\twentytwentyone\functions.php

add_action('wp_footer', 'displayHelloWorld');

Subdirectories

C:\xampp\htdocs\wordpress4\wp-content\mu-plugins\load.php

<?php  
  require(WPMU_PLUGIN_DIR . '/myplugin/myplugin.php');
?>

C:\xampp\htdocs\wordpress4\wp-content\mu-plugins\myplugin\myplugin.php

<?php  
 echo '<p style="position: fixed;bottom: 0;right: 0;padding: 10px;background-color: #0096FF;color: #FFFFFF;width: 100%;text-align: center;">Hello World!</p>';
?>

If you add a new folder containing another mu-plugin, you will have to edit the load.php file. However, you can automate this process thanks to some PHP functions. Replace the content of the load.php file by the following lines.

<?php
// Opens the must-use plugins directory
$wpmu_plugin_dir = opendir(WPMU_PLUGIN_DIR);
// Lists all the entries in this directory
while (false !== ($entry = readdir($wpmu_plugin_dir))) {
  $path = WPMU_PLUGIN_DIR . '/' . $entry;
// Is the current entry a subdirectory?
  if ($entry != '.' && $entry != '..' && is_dir($path)) {
// Includes the corresponding plugin
    require $path . '/' . $entry . '.php';
  }
}
// Closes the directory
closedir($wpmu_plugin_dir);
?>

Last updated