Posted on March 24, 2015
<?php
/**
* Remove all site capability keys when retrieving user meta
* This prevents `get_blog_details` lookups for all the sites
* a super admin is a member or admin
*
* @link https://core.trac.wordpress.org/ticket/31746#comment:1 get_blogs_of_user() can be very slow when a user is a member of thousands of sites
*/
function large_network_skip_get_blogs_of_user_with_many_sites( $null, $object_id, $meta_key ) {
global $wpdb;
// Don't proceed if fetching a specific meta key, or the current user is not a super admin
if ( $meta_key || ! is_super_admin() ) {
return $null;
}
// Ok, then fetch all the user meta (remove this filter to do so)
remove_filter( 'get_user_metadata', __FUNCTION__, 10, 4 );
$keys = get_user_meta( $object_id );
add_filter( 'get_user_metadata', __FUNCTION__, 10, 4 );
// And loop through them
foreach ( $keys as $key => $value ) {
// Ignore non-capability meta keys
if ( 'capabilities' !== substr( $key, -12 ) ) {
continue;
}
// Ignore meta keys w/o the base_prefix
if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) ) {
continue;
}
// Attempt to get the blog id from the string
$blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
// If it's not numeric, ignore this too
if ( ! is_numeric( $blog_id ) ) {
continue;
}
// Ok, let's black-list this capability meta from being sent back
unset( $keys[ $key ] );
}
return $keys;
}
add_filter( 'get_user_metadata', 'large_network_skip_get_blogs_of_user_with_many_sites', 10, 3 );
Recent Comments