Multisite: Introduce `get_site()`

Given a site ID or site object, `get_site()` retrieves site data in the same vein as `get_post()` or `get_comment()`. This will allow for clean retrieval of sites from a primed cache when `WP_Site_Query` is implemented.

Adds a `WP_Site::to_array()` method to support multiple return types within `get_site()`.

Props spacedmonkey.
See #35791.


git-svn-id: https://develop.svn.wordpress.org/trunk@37468 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Jeremy Felt 2016-05-20 04:40:39 +00:00
parent 86b5802d75
commit 898f42c2a6
2 changed files with 64 additions and 0 deletions

View File

@ -198,4 +198,16 @@ final class WP_Site {
$this->$key = $value;
}
}
/**
* Converts an object to array.
*
* @since 4.6.0
* @access public
*
* @return array Object as array.
*/
public function to_array() {
return get_object_vars( $this );
}
}

View File

@ -467,6 +467,58 @@ function clean_blog_cache( $blog ) {
do_action( 'clean_site_cache', $blog_id, $blog, $domain_path_key );
}
/**
* Retrieves site data given a site ID or site object.
*
* Site data will be cached and returned after being passed through a filter.
* If the provided site is empty, the current site global will be used.
*
* @since 4.6.0
*
* @global WP_Site $current_blog The current site.
*
* @param WP_Site|int $site Site to retrieve.
* @param string $output Optional. Type of output to return. OBJECT or ARRAY_A or ARRAY_N constants.
* @return WP_Site|array|null Depends on $output value.
*/
function get_site( &$site = null, $output = OBJECT ) {
global $current_blog;
if ( empty( $site ) && isset( $current_blog ) ) {
$site = $current_blog;
}
if ( $site instanceof WP_Site ) {
$_site = $site;
} elseif ( is_object( $site ) ) {
$_site = new WP_Site( $site );
} else {
$_site = WP_Site::get_instance( $site );
}
if ( ! $_site ) {
return null;
}
/**
* Fires after a site is retrieved.
*
* @since 4.6.0
*
* @param mixed $_site Site data.
*/
$_site = apply_filters( 'get_site', $_site );
if ( $output == OBJECT ) {
return $_site;
} elseif ( $output == ARRAY_A ) {
return $_site->to_array();
} elseif ( $output == ARRAY_N ) {
return array_values( $_site->to_array() );
}
return $_site;
}
/**
* Retrieve option value for a given blog id based on name of option.
*