I see a few things that you might try to shortcut things:
-
Currently a Multisite network only allows one site ID, according to the Codex page for
$wpdb->siteid
. Also, the site ID is defined in your wp-config.php file as a constant,BLOG_ID_CURRENT_SITE
. So any reference to$wpdb->siteid
can be replaced byBLOG_ID_CURRENT_SITE
. -
Look into the new-in-3.7 function
wp_get_sites()
. It should be able to replace your$query = "SELECT * FROM $wpdb->blogs WHERE 1=1 ";
and so forth. -
Instead of using
restore_current_blog()
after everyswitch_to_blog()
, what you can do is something like this:$current_blog = get_current_blog_id(); foreach( $site_results as $blog ) { switch_to_blog( $blog ); . . . } // end of your foreach() switch_to_blog( $current_blog );
If I’m reading your code right, you should be able to replace any $wpdb
calls with those two points. See this answer (point #3) as well — “Don’t query if you got a template tag to do the job for you”.