List all Blogs WordPress Multisite in WordPress admin bar

List all Blogs (sites) in a WordPress Multisite and show them in the WordPress admin bar.

Not long ago I was trying to list all blogs in a Multisite and show them all in the WordPress admin bar as a drop down.

The Code

class the_frosty_network {
	
	const version	= '0.3.1';
	
	function __construct() {		
		add_action( 'admin_bar_menu', array( $this, 'adminbar' ), 99 );
		add_filter( 'show_admin_bar', '__return_true', 1000 );
	}
	
	function adminbar( $wp_admin_bar ) {
		if ( !is_user_logged_in() ) {
			
    		$wp_admin_bar->add_node( array(
				'id' => 'sites', 'title' => __( 'Sites' )
			) );
			
			$this->adminbar_sites( $wp_admin_bar );
		}		
	}
	
	/**
	 * If is_multisite() query the database for all sites
	 * then cache the query and output the site's details
	 *
	 */
	function adminbar_sites( $wp_admin_bar ) {
		
		if ( !is_multisite() ) return;
		
		global $wpdb;
		
		/* http://codex.wordpress.org/WPMU_Functions/get_site_option */
		$cache = sanitize_title_with_dashes( get_site_option( 'site_name' ) ) . '_sites';
		
		/* http://codex.wordpress.org/Class_Reference/WP_Object_Cache */
		$blogs = wp_cache_get( $cache );
		
		if ( false === $blogs ) {
			$blogs = $wpdb->get_results(
				"SELECT blog_id
				FROM {$wpdb->blogs}
				WHERE site_id = '{$wpdb->siteid}'
				AND spam = '0'
				AND deleted = '0'
				AND archived = '0'
				AND public = '1'
				AND blog_id != 1"
			);
			wp_cache_set( $cache, $result );
		
			//print_r( $blogs );
			
			if ( empty( $blogs ) ) return;
			wp_cache_set( $cache, $blogs );
		}
	
		$sites = array();
		
		foreach ( $blogs as $blog ) {
			$sites[$blog->blog_id] = get_blog_details( $blog->blog_id, 'blogname' );
		}
		
		//print_r( $sites );
		
		foreach ( $sites as $blog_id => $site ) {
			$wp_admin_bar->add_node( array(
				'parent' => 'sites',
				'id' => 'site-' . $site->blog_id,
				'title' => $site->blogname,
				'href' => $site->siteurl
			) );
		}
	}
	
};
add_action( 'plugins_loaded', create_function( '', 'new the_frosty_network;' ), 9 );

For a working preview, check out demo.thefrosty.com.

Image Example

Austin
Austin

πŸ’πŸ½β€β™‚οΈ Husband to Jeana.
⚾️ Dodgers & Brewers.
πŸ’» PHP Engineer.
πŸŒπŸΌβ€β™‚οΈGolfer; ~14 HDC.
🌱 Hydroponic Gardner.
🍿 Plex nerd.
πŸš™ '15 WRX, '22 Model 3 LR, & '66 Corvette C2.

Follow me on Twitter @TheFrosty & Instagram @TheFrosty.

Articles: 292

One comment

Comments are closed.