Skip to content

Instantly share code, notes, and snippets.

@mannieschumpert
Last active December 16, 2015 10:28
Show Gist options
  • Save mannieschumpert/5420004 to your computer and use it in GitHub Desktop.
Save mannieschumpert/5420004 to your computer and use it in GitHub Desktop.
Gets/stores a transient set to an array of blog option meta for sites across a multisite network.

Network-wide queries are very costly, performance-wise. If you need to get or display lists of per-blog meta values network-wide, it's better to save it as a transient so that the query doesn't bog down the site.

####To Do:

  • remove $time parameter, and just set the expiry far in the future
  • call delete_site_transient whenever a site is added or has its status changed, or when a site modifies the specified meta
<?php
function multisite_option_transients( $option, $time ) {
// Get transient if it exists
$transient = get_site_transient($option);
// If transient isn't set, get data then set transient
if ( empty($transient) ) {
global $wpdb;
// Get an array of blog ids (omits sites deleted or flagged as spam, archived, mature)
$sites = $wpdb->get_col( $wpdb->prepare(
"SELECT blog_id FROM $wpdb->blogs
WHERE archived = %s
AND mature = '0'
AND spam = '0'
AND deleted = '0'", '0' ) ); // new prepare function requires two parameters
// Create an array of site options
if ( is_array($sites) ) {
$transient = array();
// Loop through the site IDs and get option for each
foreach ($sites as $site) {
$name = get_blog_details( $site )->blogname;
$site_option = get_blog_option( $site, $option );
$transient[$site] = array( 'name' => $name, $option => $site_option );
}
}
// Store site options array to transient
set_site_transient( $option, $transient, $time );
}
// Return transient data
return $transient;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment