pre_get_main_site_id is a WordPress PHP filter that allows you to modify the main site ID of a WordPress Multisite network.
Usage
add_filter('pre_get_main_site_id', 'your_custom_function', 10, 2);
function your_custom_function($main_site_id, $network) {
// your custom code here
return $main_site_id;
}
Parameters
$main_site_id(int|null) – The main site ID. If a positive integer is returned, it is interpreted as the main site ID.$network(WP_Network) – The network object for which the main site was detected.
More information
See WordPress Developer Resources: pre_get_main_site_id
Examples
Change the main site ID
Change the main site ID to a different ID.
add_filter('pre_get_main_site_id', 'change_main_site_id', 10, 2);
function change_main_site_id($main_site_id, $network) {
// Set the new main site ID
$new_main_site_id = 5;
return $new_main_site_id;
}
Set the main site ID based on the network
Set the main site ID based on the network ID.
add_filter('pre_get_main_site_id', 'set_main_site_based_on_network', 10, 2);
function set_main_site_based_on_network($main_site_id, $network) {
// Set the main site ID based on the network ID
if ($network->id == 2) {
return 10;
}
return $main_site_id;
}
Set the main site ID conditionally
Set the main site ID based on a custom condition.
add_filter('pre_get_main_site_id', 'conditional_main_site_id', 10, 2);
function conditional_main_site_id($main_site_id, $network) {
// Set the main site ID if the current user is an administrator
if (current_user_can('administrator')) {
return 3;
}
return $main_site_id;
}
Log the main site ID
Log the main site ID in a text file.
add_filter('pre_get_main_site_id', 'log_main_site_id', 10, 2);
function log_main_site_id($main_site_id, $network) {
// Log the main site ID
error_log("Main Site ID: " . $main_site_id . "\n", 3, "/path/to/your_log_file.txt");
return $main_site_id;
}
Display a notice with the main site ID
Display an admin notice with the main site ID.
add_filter('pre_get_main_site_id', 'display_main_site_id_notice', 10, 2);
function display_main_site_id_notice($main_site_id, $network) {
// Display an admin notice with the main site ID
add_action('admin_notices', function() use ($main_site_id) {
echo '<div class="notice notice-info"><p>Main Site ID: ' . $main_site_id . '</p></div>';
});
return $main_site_id;
}