From 898f42c2a66bb7b106bc38c0db35cf156345cee1 Mon Sep 17 00:00:00 2001 From: Jeremy Felt Date: Fri, 20 May 2016 04:40:39 +0000 Subject: [PATCH] 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 --- src/wp-includes/class-wp-site.php | 12 +++++++ src/wp-includes/ms-blogs.php | 52 +++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/src/wp-includes/class-wp-site.php b/src/wp-includes/class-wp-site.php index 5de6b9f2ca..20d15344c1 100644 --- a/src/wp-includes/class-wp-site.php +++ b/src/wp-includes/class-wp-site.php @@ -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 ); + } } diff --git a/src/wp-includes/ms-blogs.php b/src/wp-includes/ms-blogs.php index 0a1f6e3c3a..1f5c652a1c 100644 --- a/src/wp-includes/ms-blogs.php +++ b/src/wp-includes/ms-blogs.php @@ -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. *