Using WordPress ‘ms_loaded’ PHP action

The ms_loaded WordPress action fires after the current site and network have been detected and loaded in a multisite’s bootstrap.

Usage

add_action('ms_loaded', 'my_custom_function');

function my_custom_function() {
    // your custom code here
}

Parameters

  • None

More information

See WordPress Developer Resources: ms_loaded

Examples

Redirect non-logged-in users to a specific page

In this example, we’ll redirect non-logged-in users to the login page.

add_action('ms_loaded', 'redirect_non_logged_in_users');

function redirect_non_logged_in_users() {
    if (!is_user_logged_in()) {
        wp_redirect(wp_login_url());
        exit;
    }
}

Perform maintenance on all sites in a multisite network

This example runs a custom maintenance function on all sites within a multisite network.

add_action('ms_loaded', 'perform_maintenance_on_all_sites');

function perform_maintenance_on_all_sites() {
    if (is_multisite()) {
        $sites = get_sites();
        foreach ($sites as $site) {
            switch_to_blog($site->blog_id);
            // your custom maintenance code here
            restore_current_blog();
        }
    }
}

Add a global admin notice on all sites in a multisite network

This example adds a global admin notice visible on all sites within a multisite network.

add_action('ms_loaded', 'add_global_admin_notice');

function add_global_admin_notice() {
    add_action('admin_notices', 'display_global_admin_notice');
}

function display_global_admin_notice() {
    echo '<div class="notice notice-warning is-dismissible"><p>**This is a global admin notice.**</p></div>';
}

This example sets a custom cookie when the multisite network is loaded.

add_action('ms_loaded', 'set_custom_cookie');

function set_custom_cookie() {
    setcookie('my_custom_cookie', 'cookie_value', time() + 3600, '/');
}

Apply a custom filter to the site title for all sites in a multisite network

In this example, we’ll apply a custom filter to the site title for all sites in a multisite network.

add_action('ms_loaded', 'add_custom_title_filter_to_all_sites');

function add_custom_title_filter_to_all_sites() {
    if (is_multisite()) {
        add_filter('wp_title', 'apply_custom_title_filter');
    }
}

function apply_custom_title_filter($title) {
    return '**Custom Title Prefix:** ' . $title;
}