List sites from your network

List sites from your network

Let’s start with an interesting snippet for those who run networks of many blogs. The code below display a general menu of all sites from your networks. In this case, transients are used to store the data for a defined time (which can be set using the $expires variable on line 1) so you’ll not make huge database calls each time your menu have to be displayed.

To use this snippet, first you have to paste the function into your functions.php file.

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 = ‘

‘ . “n”;

foreach ( $site_list as $site ) { switch_to_blog( $site->blog_id ); $class = ( home_url() == $current_site_url ) ? ‘ class=”current-site-item”‘ : ”; $html .= “t” . ‘