Skip to main content
Login Join
Snippet · PHP

Register a Must-Use Plugin Programmatically

Shared by Jainil Nagar · June 15, 2026 · @muplugins_loaded

18 views
Back to Snippets
/**
 * Bootstrap file for a Must-Use (MU) plugin.
 *
 * File location: /wp-content/mu-plugins/wpfolks-enforced.php
 *
 * MU plugins:
 * - Load automatically before regular plugins
 * - Cannot be deactivated via the admin UI
 * - Do not appear in the standard Plugins list (only in Must-Use tab)
 * - Ideal for enforcing security policies, logging, or site-wide hooks
 *
 * Plugin Name:  WPFolks Enforced Settings
 * Description:  Site-wide enforced configuration that cannot be disabled.
 * Version:      1.0.0
 * Author:       Your Name
 */

// Guard: only run in WordPress context
if ( ! defined( 'ABSPATH' ) ) exit;

add_action( 'muplugins_loaded', 'wpfolks_enforced_init' );
function wpfolks_enforced_init(): void {

    // Example 1: Always disable file editing — hardened beyond wp-config.php
    if ( ! defined( 'DISALLOW_FILE_EDIT' ) ) {
        define( 'DISALLOW_FILE_EDIT', true );
    }

    // Example 2: Force HTTPS on all admin requests
    add_action( 'admin_init', function (): void {
        if ( ! is_ssl() && ! wp_doing_ajax() ) {
            wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
            exit;
        }
    } );

    // Example 3: Enforce a minimum PHP version — fail gracefully
    if ( version_compare( PHP_VERSION, '8.1', '<' ) ) {
        add_action( 'admin_notices', function (): void {
            echo '<div class="notice notice-error"><p>'
                . esc_html__( 'This site requires PHP 8.1 or higher. Please upgrade your PHP version.', 'textdomain' )
                . '</p></div>';
        } );
        return; // Stop loading further enforced functionality
    }

    // Example 4: Prevent any plugin from removing core security headers
    add_action( 'send_headers', function (): void {
        if ( headers_sent() ) return;
        header( 'X-Content-Type-Options: nosniff' );
        header( 'X-Frame-Options: SAMEORIGIN' );
        header( 'Referrer-Policy: strict-origin-when-cross-origin' );
    }, 999 ); // High priority to run last
}
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments