WordPress hack: How to build a network navigation menu

January 10, 2012 at 5:10 pm

Multisites networks are definitely a great feature introduced in WP 3.0+. In this recipe, you’re going to learn how you can create a “network” navigation menu, which list all sites on your network.

The first thing to do is to create the function. Paste the code below into your functions.php file:

/**
 * Build a list of all websites in a network
 */
function wp_list_sites( $expires = 7200 ) {
   if( !is_multisite() ) return false;

   // Because the get_blog_list() function is currently flagged as deprecated
   // due to the potential for high consumption of resources, we'll use
   // $wpdb to roll out our own SQL query instead. Because the query can be
   // memory-intensive, we'll store the results using the Transients API
   if ( false === ( $site_list = get_transient( 'multisite_site_list' ) ) ) {
      global $wpdb;
      $site_list = $wpdb->get_results( $wpdb->prepare('SELECT * FROM wp_blogs ORDER BY blog_id') );
      // Set the Transient cache to expire every two hours
      set_site_transient( 'multisite_site_list', $site_list, $expires );
   }

   $current_site_url = get_site_url( get_current_blog_id() );

   $html = '
<ul id="network-menu">' . "\n";

   foreach ( $site_list as $site ) {
      switch_to_blog( $site->blog_id );
      $class = ( home_url() == $current_site_url ) ? ' class="current-site-item"' : '';
      $html .= "\t" . '
<li id="site-' . $site->blog_id . '" '="" .="" $class=""><a href="' . home_url() . '">' . get_bloginfo('name') . '</a></li>

' . "\n";
      restore_current_blog();
   }

   $html .= '</ul>

<!--// end #network-menu -->' . "\n\n";

   return $html;
}

Once done, you can use the wp_list_sites() function in your theme files. The example below shows how it works:

<?php
// Multisite Network Menu
$network_menu = wp_list_sites();
if( $network_menu ):
?>
<div id="network-menu">
   <?php echo $network_menu; ?>
</div>

<!--// end #network-menu -->
<?php endif; ?>

Thanks to Kevin Leary for the great hack!