Webmaster Hub

How to show the number of sites on a WordPress Multisite Network

If you’re running WordPress Multisite, there’s a good chance you might want to show off the amount of sites on your network. This is especially relevant if you’re trying to get users to sign up for your network, as users have a tendancy to judge a service by its popularity.

Screenshot_3_01_13_9_24_PM-2

You can retrieve the number of users on a network with the following SQL query:
[sourcecode language=”sql”]select count(*) from wp_blogs where deleted = 0[/sourcecode]

Obviously you can’t just embed SQL into a WordPress post/page for security reasons, so you will need to create a function to retrieve the data. You can add the following to your functions.php file and then call get_site_count(); in your theme files.

function get_site_count(){
	global $wpdb;
	$id = 0;
	$site_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM wp_blogs WHERE deleted = %d",$id));
	return $site_count;
}

What if you want to use this function in posts or pages? The easiest way is by creating a custom shortcode. WordPress lets you do it in a single line of code.

add_shortcode('sitecount', 'get_site_count');

With that added to your function.php file, you can easily display the number of sites on your network by typing [sitecount] into the content editor.

There’s only one problem with this approach. If you change theme (or use multiple themes across your network) placing this code in every theme functions file can become tedious. I recommend creating a custom Must Use Plugin and installing it in wp-content/mu-plugins/.

The full code for the plugin can be found below. You can also download it here, but make sure you unzip it before uploading into /mu-plugins/.

<?php
/*
Plugin Name: Multisite Site Count Shortcode
Plugin URI: http://shanegowland.com/wordpress/2013/show-the-number-of-sites-on-a-wordpress-network/
Description: Allows you to display the total number of sites on a WordPress Network
Version: 1.0
Author: Shane Gowland
Author URI: http://shanegowland.com
License: GPL2

*/

function get_site_count(){
	global $wpdb;
	$id = 0;
	$site_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM wp_blogs WHERE deleted = %d",$id));
	return $site_count;
}
//register the shortcode
add_shortcode('sitecount', 'get_site_count');  

In the post editor, just add the shortcode as shown:
Shortcode in editor


Leave a Reply