What are mu-plugins in WordPress and how to create one?

In the vast universe of WordPress, mu-plugins (Must Use Plugins) are a powerful yet often underestimated tool. These special plugins are automatically loaded on all WordPress sites without the need for individual activation, making them an ideal choice for critical site functionalities or for establishing global settings.

 

Why use mu-plugins?

Mu-plugins offer several advantages:

  1. Automatic Loading: They are automatically activated without the need for user intervention.
  2. Load Priority: They load before regular plugins, ensuring that their functionality is available early in the loading process.
  3. Global Functionality: They are ideal for functionalities that need to be available on all sites of a WordPress multisite installation.
  4. Cannot be Deactivated: This prevents critical functionality from being accidentally disabled.

Creating a mu-plugin

Creating a mu-plugin is quite simple. Follow these steps to create one from scratch:

Step 1: Access the mu-plugins directory

First, access the mu-plugins directory of your WordPress installation. This directory is located at wp-content/mu-plugins/. If it doesn’t exist, create it.

Step 2: Create a new PHP file

Inside the mu-plugins directory, create a new PHP file with the name you prefer. For example, my-mu-plugin.php.

Step 3: Write your code

Now, you can write the PHP code for your mu-plugin. Here’s a basic example that adds a greeting functionality at the top of each page of the site:

<?php
/*
Plugin Name: My Must Use Plugin
Description: This is an example of a mu-plugin that displays a greeting at the top of every page.
*/

// Add greeting at the top of each page
function add_greeting() {
    echo '<div style="background-color: #f0f0f0; padding: 10px; text-align: center;">Hello! This is a message from my mu-plugin.</div>';
}
add_action('wp_head', 'add_greeting');

 

 

This code creates a new plugin that will display a greeting at the top of each page of the site.

Step 4: Save and activate

Save the file, and your mu-plugin will be active immediately. You don’t need to activate it in the WordPress plugins section, as mu-plugins are automatically activated.

Mu-plugins are a powerful tool for customizing and extending WordPress. Being automatically loaded and with no possibility of accidental deactivation, they are ideal for critical or global functionalities on your site. Make the most out of this functionality in your next WordPress project!

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x