Sarathlal N

Display all sites in a network as a drop down list – WordPress

When creating WordPress network sites, regularly I want to display all sites in that network as a drop down in front end.

We can use a simple code snippet that useĀ wpdb class to get such a list.

<?php
global $wpdb;
$blogs = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->blogs WHERE spam = '0' AND deleted = '0' and archived = '0' and public='1'"));
if(!empty($blogs)){
 ?>
	 <select onChange="window.document.location.href=this.options[this.selectedIndex].value;" value="GO">
	 <?php
		 foreach($blogs as $blog){
		 $details = get_blog_details($blog->blog_id);
			 if($details != false){
				$addr = $details->siteurl;
				$name = $details->blogname;
					if(!(($blog->blog_id == 1)&&($show_main != 1))){ //This if statement that hide main site from list. So comment or uncomment this line with below closing tag
					?>
					<option value="<?php echo $addr; ?>"><?php echo $name;?></option>
					<?php
					} //End of if statement
			 }
		 }
	 ?>
	 </select>
 <?php
}
?> 

Looking for a skilled WordPress/WooCommerce developer? I'm currently available for freelance, contract, or full-time remote opportunities! Let's create something amazing together. Send me a quick message, and I'll respond within 24 hours!

Recent Posts

  1. Scaling WordPress - How Custom Database Tables Solve the Post Meta Bottleneck
  2. WordPress Transients Explained - A Developer's Guide to Site Performance
  3. Behind the Click - The Hidden Journey of Your Web Requests
  4. Automating Code Linting with GitHub Actions for WordPress Plugins
  5. Comprehensive Guide to Linting PHP, JavaScript, and CSS in WordPress Plugins Using Composer

Your Questions / Comments

If you found this article interesting, found errors, or just want to discuss about it, please get in touch.