How to get the main blog’s id and db prefix from a mu plugin?

How can one get the blog ID as well as the database prefix of the main blog in a wordpress multisite installation? Is the main blog’s ID always 1? Also how can the main blog’s table prefix be acquired from within the mu-plugin’s code?

Related posts

Leave a Reply

4 comments

  1. This is how we do it to be 100% as we have multiple main sites in the network installation:

    function name_ly_get_main_blog_id () {
      global $current_site;
      global $wpdb;
    
      return $wpdb->get_var ( $wpdb->prepare ( "SELECT `blog_id` FROM `$wpdb->blogs` WHERE `domain` = '%s' AND `path` = '%s' ORDER BY `blog_id` ASC LIMIT 1", $current_site->domain, $current_site->path ) );
    }
    
  2. There’s a function to get main site id for a given network (defaults to the active network)

    get_main_site_id();
    

    If you only need db prefix, $wpdb->get_blog_prefix(get_main_site_id()) would suffice, but otherwise you can switch whole code blocks into other blog’s context seamlessly with switch_to_blog() and restore_current_blog() functions

    switch_to_blog(get_main_site_id());
    global $wpdb; // it's now in the main site's context
    $prefix = $wpdb->prefix;
    // ... do your stuff
    restore_current_blog();
    

    But be wary of recursive calls to switch_to_blog(), because then context becomes hard to track and debug