9 final class WP_Theme implements ArrayAccess {
12 * Whether the theme has been marked as updateable.
18 * @see WP_MS_Themes_List_Table
20 public $update = false;
23 * Headers for style.css files.
29 private static $file_headers = array(
30 'Name' => 'Theme Name',
31 'ThemeURI' => 'Theme URI',
32 'Description' => 'Description',
34 'AuthorURI' => 'Author URI',
35 'Version' => 'Version',
36 'Template' => 'Template',
39 'TextDomain' => 'Text Domain',
40 'DomainPath' => 'Domain Path',
50 private static $default_themes = array(
51 'classic' => 'WordPress Classic',
52 'default' => 'WordPress Default',
53 'twentyten' => 'Twenty Ten',
54 'twentyeleven' => 'Twenty Eleven',
55 'twentytwelve' => 'Twenty Twelve',
56 'twentythirteen' => 'Twenty Thirteen',
57 'twentyfourteen' => 'Twenty Fourteen',
58 'twentyfifteen' => 'Twenty Fifteen',
59 'twentysixteen' => 'Twenty Sixteen',
60 'twentyseventeen' => 'Twenty Seventeen',
70 private static $tag_map = array(
71 'fixed-width' => 'fixed-layout',
72 'flexible-width' => 'fluid-layout',
76 * Absolute path to the theme root, usually wp-content/themes
84 * Header data from the theme's style.css file.
89 private $headers = array();
92 * Header data from the theme's style.css file after being sanitized.
97 private $headers_sanitized;
100 * Header name from the theme's style.css after being translated.
102 * Cached due to sorting functions running over the translated name.
107 private $name_translated;
110 * Errors encountered when initializing the theme.
118 * The directory name of the theme's files, inside the theme root.
120 * In the case of a child theme, this is directory name of the child theme.
121 * Otherwise, 'stylesheet' is the same as 'template'.
129 * The directory name of the theme's files, inside the theme root.
131 * In the case of a child theme, this is the directory name of the parent theme.
132 * Otherwise, 'template' is the same as 'stylesheet'.
140 * A reference to the parent theme, in the case of a child theme.
148 * URL to the theme root, usually an absolute URL to wp-content/themes
153 private $theme_root_uri;
156 * Flag for whether the theme's textdomain is loaded.
161 private $textdomain_loaded;
164 * Stores an md5 hash of the theme root, to function as the cache key.
172 * Flag for whether the themes cache bucket should be persistently cached.
174 * Default is false. Can be set with the {@see 'wp_cache_themes_persistently'} filter.
180 private static $persistently_cache;
183 * Expiration time for the themes cache bucket.
185 * By default the bucket is not cached, so this value is useless.
191 private static $cache_expiration = 1800;
194 * Constructor for WP_Theme.
196 * @global array $wp_theme_directories
198 * @param string $theme_dir Directory of the theme within the theme_root.
199 * @param string $theme_root Theme root.
200 * @param WP_Error|void $_child If this theme is a parent theme, the child may be passed for validation purposes.
202 public function __construct( $theme_dir, $theme_root, $_child = null ) {
203 global $wp_theme_directories;
205 // Initialize caching on first run.
206 if ( ! isset( self::$persistently_cache ) ) {
207 /** This action is documented in wp-includes/theme.php */
208 self::$persistently_cache = apply_filters( 'wp_cache_themes_persistently', false, 'WP_Theme' );
209 if ( self::$persistently_cache ) {
210 wp_cache_add_global_groups( 'themes' );
211 if ( is_int( self::$persistently_cache ) )
212 self::$cache_expiration = self::$persistently_cache;
214 wp_cache_add_non_persistent_groups( 'themes' );
218 $this->theme_root = $theme_root;
219 $this->stylesheet = $theme_dir;
221 // Correct a situation where the theme is 'some-directory/some-theme' but 'some-directory' was passed in as part of the theme root instead.
222 if ( ! in_array( $theme_root, (array) $wp_theme_directories ) && in_array( dirname( $theme_root ), (array) $wp_theme_directories ) ) {
223 $this->stylesheet = basename( $this->theme_root ) . '/' . $this->stylesheet;
224 $this->theme_root = dirname( $theme_root );
227 $this->cache_hash = md5( $this->theme_root . '/' . $this->stylesheet );
228 $theme_file = $this->stylesheet . '/style.css';
230 $cache = $this->cache_get( 'theme' );
232 if ( is_array( $cache ) ) {
233 foreach ( array( 'errors', 'headers', 'template' ) as $key ) {
234 if ( isset( $cache[ $key ] ) )
235 $this->$key = $cache[ $key ];
239 if ( isset( $cache['theme_root_template'] ) )
240 $theme_root_template = $cache['theme_root_template'];
241 } elseif ( ! file_exists( $this->theme_root . '/' . $theme_file ) ) {
242 $this->headers['Name'] = $this->stylesheet;
243 if ( ! file_exists( $this->theme_root . '/' . $this->stylesheet ) )
244 $this->errors = new WP_Error( 'theme_not_found', sprintf( __( 'The theme directory "%s" does not exist.' ), esc_html( $this->stylesheet ) ) );
246 $this->errors = new WP_Error( 'theme_no_stylesheet', __( 'Stylesheet is missing.' ) );
247 $this->template = $this->stylesheet;
248 $this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
249 if ( ! file_exists( $this->theme_root ) ) // Don't cache this one.
250 $this->errors->add( 'theme_root_missing', __( 'ERROR: The themes directory is either empty or doesn’t exist. Please check your installation.' ) );
252 } elseif ( ! is_readable( $this->theme_root . '/' . $theme_file ) ) {
253 $this->headers['Name'] = $this->stylesheet;
254 $this->errors = new WP_Error( 'theme_stylesheet_not_readable', __( 'Stylesheet is not readable.' ) );
255 $this->template = $this->stylesheet;
256 $this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
259 $this->headers = get_file_data( $this->theme_root . '/' . $theme_file, self::$file_headers, 'theme' );
260 // Default themes always trump their pretenders.
261 // Properly identify default themes that are inside a directory within wp-content/themes.
262 if ( $default_theme_slug = array_search( $this->headers['Name'], self::$default_themes ) ) {
263 if ( basename( $this->stylesheet ) != $default_theme_slug )
264 $this->headers['Name'] .= '/' . $this->stylesheet;
268 // (If template is set from cache [and there are no errors], we know it's good.)
269 if ( ! $this->template && ! ( $this->template = $this->headers['Template'] ) ) {
270 $this->template = $this->stylesheet;
271 if ( ! file_exists( $this->theme_root . '/' . $this->stylesheet . '/index.php' ) ) {
272 $error_message = sprintf(
273 /* translators: 1: index.php, 2: Codex URL, 3: style.css */
274 __( 'Template is missing. Standalone themes need to have a %1$s template file. <a href="%2$s">Child themes</a> need to have a Template header in the %3$s stylesheet.' ),
275 '<code>index.php</code>',
276 __( 'https://codex.wordpress.org/Child_Themes' ),
277 '<code>style.css</code>'
279 $this->errors = new WP_Error( 'theme_no_index', $error_message );
280 $this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
285 // If we got our data from cache, we can assume that 'template' is pointing to the right place.
286 if ( ! is_array( $cache ) && $this->template != $this->stylesheet && ! file_exists( $this->theme_root . '/' . $this->template . '/index.php' ) ) {
287 // If we're in a directory of themes inside /themes, look for the parent nearby.
288 // wp-content/themes/directory-of-themes/*
289 $parent_dir = dirname( $this->stylesheet );
290 if ( '.' != $parent_dir && file_exists( $this->theme_root . '/' . $parent_dir . '/' . $this->template . '/index.php' ) ) {
291 $this->template = $parent_dir . '/' . $this->template;
292 } elseif ( ( $directories = search_theme_directories() ) && isset( $directories[ $this->template ] ) ) {
293 // Look for the template in the search_theme_directories() results, in case it is in another theme root.
294 // We don't look into directories of themes, just the theme root.
295 $theme_root_template = $directories[ $this->template ]['theme_root'];
297 // Parent theme is missing.
298 $this->errors = new WP_Error( 'theme_no_parent', sprintf( __( 'The parent theme is missing. Please install the "%s" parent theme.' ), esc_html( $this->template ) ) );
299 $this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
300 $this->parent = new WP_Theme( $this->template, $this->theme_root, $this );
305 // Set the parent, if we're a child theme.
306 if ( $this->template != $this->stylesheet ) {
307 // If we are a parent, then there is a problem. Only two generations allowed! Cancel things out.
308 if ( $_child instanceof WP_Theme && $_child->template == $this->stylesheet ) {
309 $_child->parent = null;
310 $_child->errors = new WP_Error( 'theme_parent_invalid', sprintf( __( 'The "%s" theme is not a valid parent theme.' ), esc_html( $_child->template ) ) );
311 $_child->cache_add( 'theme', array( 'headers' => $_child->headers, 'errors' => $_child->errors, 'stylesheet' => $_child->stylesheet, 'template' => $_child->template ) );
312 // The two themes actually reference each other with the Template header.
313 if ( $_child->stylesheet == $this->template ) {
314 $this->errors = new WP_Error( 'theme_parent_invalid', sprintf( __( 'The "%s" theme is not a valid parent theme.' ), esc_html( $this->template ) ) );
315 $this->cache_add( 'theme', array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template ) );
319 // Set the parent. Pass the current instance so we can do the crazy checks above and assess errors.
320 $this->parent = new WP_Theme( $this->template, isset( $theme_root_template ) ? $theme_root_template : $this->theme_root, $this );
323 // We're good. If we didn't retrieve from cache, set it.
324 if ( ! is_array( $cache ) ) {
325 $cache = array( 'headers' => $this->headers, 'errors' => $this->errors, 'stylesheet' => $this->stylesheet, 'template' => $this->template );
326 // If the parent theme is in another root, we'll want to cache this. Avoids an entire branch of filesystem calls above.
327 if ( isset( $theme_root_template ) )
328 $cache['theme_root_template'] = $theme_root_template;
329 $this->cache_add( 'theme', $cache );
334 * When converting the object to a string, the theme name is returned.
336 * @return string Theme name, ready for display (translated)
338 public function __toString() {
339 return (string) $this->display('Name');
343 * __isset() magic method for properties formerly returned by current_theme_info()
345 * @staticvar array $properties
347 * @param string $offset Property to check if set.
348 * @return bool Whether the given property is set.
350 public function __isset( $offset ) {
351 static $properties = array(
352 'name', 'title', 'version', 'parent_theme', 'template_dir', 'stylesheet_dir', 'template', 'stylesheet',
353 'screenshot', 'description', 'author', 'tags', 'theme_root', 'theme_root_uri',
356 return in_array( $offset, $properties );
360 * __get() magic method for properties formerly returned by current_theme_info()
362 * @param string $offset Property to get.
363 * @return mixed Property value.
365 public function __get( $offset ) {
369 return $this->get('Name');
371 return $this->get('Version');
372 case 'parent_theme' :
373 return $this->parent() ? $this->parent()->get('Name') : '';
374 case 'template_dir' :
375 return $this->get_template_directory();
376 case 'stylesheet_dir' :
377 return $this->get_stylesheet_directory();
379 return $this->get_template();
381 return $this->get_stylesheet();
383 return $this->get_screenshot( 'relative' );
384 // 'author' and 'description' did not previously return translated data.
386 return $this->display('Description');
388 return $this->display('Author');
390 return $this->get( 'Tags' );
392 return $this->get_theme_root();
393 case 'theme_root_uri' :
394 return $this->get_theme_root_uri();
395 // For cases where the array was converted to an object.
397 return $this->offsetGet( $offset );
402 * Method to implement ArrayAccess for keys formerly returned by get_themes()
404 * @param mixed $offset
405 * @param mixed $value
407 public function offsetSet( $offset, $value ) {}
410 * Method to implement ArrayAccess for keys formerly returned by get_themes()
412 * @param mixed $offset
414 public function offsetUnset( $offset ) {}
417 * Method to implement ArrayAccess for keys formerly returned by get_themes()
419 * @staticvar array $keys
421 * @param mixed $offset
424 public function offsetExists( $offset ) {
425 static $keys = array(
426 'Name', 'Version', 'Status', 'Title', 'Author', 'Author Name', 'Author URI', 'Description',
427 'Template', 'Stylesheet', 'Template Files', 'Stylesheet Files', 'Template Dir', 'Stylesheet Dir',
428 'Screenshot', 'Tags', 'Theme Root', 'Theme Root URI', 'Parent Theme',
431 return in_array( $offset, $keys );
435 * Method to implement ArrayAccess for keys formerly returned by get_themes().
437 * Author, Author Name, Author URI, and Description did not previously return
438 * translated data. We are doing so now as it is safe to do. However, as
439 * Name and Title could have been used as the key for get_themes(), both remain
440 * untranslated for back compatibility. This means that ['Name'] is not ideal,
441 * and care should be taken to use `$theme::display( 'Name' )` to get a properly
444 * @param mixed $offset
447 public function offsetGet( $offset ) {
452 * See note above about using translated data. get() is not ideal.
453 * It is only for backward compatibility. Use display().
455 return $this->get('Name');
457 return $this->display( 'Author');
459 return $this->display( 'Author', false);
461 return $this->display('AuthorURI');
463 return $this->display( 'Description');
466 return $this->get( $offset );
468 return $this->get_template();
470 return $this->get_stylesheet();
471 case 'Template Files' :
472 return $this->get_files( 'php', 1, true );
473 case 'Stylesheet Files' :
474 return $this->get_files( 'css', 0, false );
475 case 'Template Dir' :
476 return $this->get_template_directory();
477 case 'Stylesheet Dir' :
478 return $this->get_stylesheet_directory();
480 return $this->get_screenshot( 'relative' );
482 return $this->get('Tags');
484 return $this->get_theme_root();
485 case 'Theme Root URI' :
486 return $this->get_theme_root_uri();
487 case 'Parent Theme' :
488 return $this->parent() ? $this->parent()->get('Name') : '';
495 * Returns errors property.
500 * @return WP_Error|false WP_Error if there are errors, or false.
502 public function errors() {
503 return is_wp_error( $this->errors ) ? $this->errors : false;
507 * Whether the theme exists.
509 * A theme with errors exists. A theme with the error of 'theme_not_found',
510 * meaning that the theme's directory was not found, does not exist.
515 * @return bool Whether the theme exists.
517 public function exists() {
518 return ! ( $this->errors() && in_array( 'theme_not_found', $this->errors()->get_error_codes() ) );
522 * Returns reference to the parent theme.
527 * @return WP_Theme|false Parent theme, or false if the current theme is not a child theme.
529 public function parent() {
530 return isset( $this->parent ) ? $this->parent : false;
534 * Adds theme data to cache.
536 * Cache entries keyed by the theme and the type of data.
541 * @param string $key Type of data to store (theme, screenshot, headers, post_templates)
542 * @param string $data Data to store
543 * @return bool Return value from wp_cache_add()
545 private function cache_add( $key, $data ) {
546 return wp_cache_add( $key . '-' . $this->cache_hash, $data, 'themes', self::$cache_expiration );
550 * Gets theme data from cache.
552 * Cache entries are keyed by the theme and the type of data.
557 * @param string $key Type of data to retrieve (theme, screenshot, headers, post_templates)
558 * @return mixed Retrieved data
560 private function cache_get( $key ) {
561 return wp_cache_get( $key . '-' . $this->cache_hash, 'themes' );
565 * Clears the cache for the theme.
570 public function cache_delete() {
571 foreach ( array( 'theme', 'screenshot', 'headers', 'post_templates' ) as $key )
572 wp_cache_delete( $key . '-' . $this->cache_hash, 'themes' );
573 $this->template = $this->textdomain_loaded = $this->theme_root_uri = $this->parent = $this->errors = $this->headers_sanitized = $this->name_translated = null;
574 $this->headers = array();
575 $this->__construct( $this->stylesheet, $this->theme_root );
579 * Get a raw, unformatted theme header.
581 * The header is sanitized, but is not translated, and is not marked up for display.
582 * To get a theme header for display, use the display() method.
584 * Use the get_template() method, not the 'Template' header, for finding the template.
585 * The 'Template' header is only good for what was written in the style.css, while
586 * get_template() takes into account where WordPress actually located the theme and
587 * whether it is actually valid.
592 * @param string $header Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags.
593 * @return string|false String on success, false on failure.
595 public function get( $header ) {
596 if ( ! isset( $this->headers[ $header ] ) )
599 if ( ! isset( $this->headers_sanitized ) ) {
600 $this->headers_sanitized = $this->cache_get( 'headers' );
601 if ( ! is_array( $this->headers_sanitized ) )
602 $this->headers_sanitized = array();
605 if ( isset( $this->headers_sanitized[ $header ] ) )
606 return $this->headers_sanitized[ $header ];
608 // If themes are a persistent group, sanitize everything and cache it. One cache add is better than many cache sets.
609 if ( self::$persistently_cache ) {
610 foreach ( array_keys( $this->headers ) as $_header )
611 $this->headers_sanitized[ $_header ] = $this->sanitize_header( $_header, $this->headers[ $_header ] );
612 $this->cache_add( 'headers', $this->headers_sanitized );
614 $this->headers_sanitized[ $header ] = $this->sanitize_header( $header, $this->headers[ $header ] );
617 return $this->headers_sanitized[ $header ];
621 * Gets a theme header, formatted and translated for display.
626 * @param string $header Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags.
627 * @param bool $markup Optional. Whether to mark up the header. Defaults to true.
628 * @param bool $translate Optional. Whether to translate the header. Defaults to true.
629 * @return string|false Processed header, false on failure.
631 public function display( $header, $markup = true, $translate = true ) {
632 $value = $this->get( $header );
633 if ( false === $value ) {
637 if ( $translate && ( empty( $value ) || ! $this->load_textdomain() ) )
641 $value = $this->translate_header( $header, $value );
644 $value = $this->markup_header( $header, $value, $translate );
650 * Sanitize a theme header.
655 * @staticvar array $header_tags
656 * @staticvar array $header_tags_with_a
658 * @param string $header Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags.
659 * @param string $value Value to sanitize.
662 private function sanitize_header( $header, $value ) {
669 // Fall through otherwise.
671 static $header_tags = array(
672 'abbr' => array( 'title' => true ),
673 'acronym' => array( 'title' => true ),
678 $value = wp_kses( $value, $header_tags );
681 // There shouldn't be anchor tags in Author, but some themes like to be challenging.
683 static $header_tags_with_a = array(
684 'a' => array( 'href' => true, 'title' => true ),
685 'abbr' => array( 'title' => true ),
686 'acronym' => array( 'title' => true ),
691 $value = wp_kses( $value, $header_tags_with_a );
695 $value = esc_url_raw( $value );
698 $value = array_filter( array_map( 'trim', explode( ',', strip_tags( $value ) ) ) );
701 $value = strip_tags( $value );
709 * Mark up a theme header.
714 * @staticvar string $comma
716 * @param string $header Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags.
717 * @param string $value Value to mark up.
718 * @param string $translate Whether the header has been translated.
719 * @return string Value, marked up.
721 private function markup_header( $header, $value, $translate ) {
724 if ( empty( $value ) )
725 $value = $this->get_stylesheet();
728 $value = wptexturize( $value );
731 if ( $this->get('AuthorURI') ) {
732 $value = sprintf( '<a href="%1$s">%2$s</a>', $this->display( 'AuthorURI', true, $translate ), $value );
733 } elseif ( ! $value ) {
734 $value = __( 'Anonymous' );
738 static $comma = null;
739 if ( ! isset( $comma ) ) {
740 /* translators: used between list items, there is a space after the comma */
743 $value = implode( $comma, $value );
747 $value = esc_url( $value );
755 * Translate a theme header.
760 * @staticvar array $tags_list
762 * @param string $header Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags.
763 * @param string $value Value to translate.
764 * @return string Translated value.
766 private function translate_header( $header, $value ) {
769 // Cached for sorting reasons.
770 if ( isset( $this->name_translated ) )
771 return $this->name_translated;
772 $this->name_translated = translate( $value, $this->get('TextDomain' ) );
773 return $this->name_translated;
775 if ( empty( $value ) || ! function_exists( 'get_theme_feature_list' ) ) {
780 if ( ! isset( $tags_list ) ) {
782 // As of 4.6, deprecated tags which are only used to provide translation for older themes.
783 'black' => __( 'Black' ), 'blue' => __( 'Blue' ), 'brown' => __( 'Brown' ),
784 'gray' => __( 'Gray' ), 'green' => __( 'Green' ), 'orange' => __( 'Orange' ),
785 'pink' => __( 'Pink' ), 'purple' => __( 'Purple' ), 'red' => __( 'Red' ),
786 'silver' => __( 'Silver' ), 'tan' => __( 'Tan' ), 'white' => __( 'White' ),
787 'yellow' => __( 'Yellow' ), 'dark' => __( 'Dark' ), 'light' => __( 'Light' ),
788 'fixed-layout' => __( 'Fixed Layout' ), 'fluid-layout' => __( 'Fluid Layout' ),
789 'responsive-layout' => __( 'Responsive Layout' ), 'blavatar' => __( 'Blavatar' ),
790 'photoblogging' => __( 'Photoblogging' ), 'seasonal' => __( 'Seasonal' ),
793 $feature_list = get_theme_feature_list( false ); // No API
794 foreach ( $feature_list as $tags ) {
799 foreach ( $value as &$tag ) {
800 if ( isset( $tags_list[ $tag ] ) ) {
801 $tag = $tags_list[ $tag ];
802 } elseif ( isset( self::$tag_map[ $tag ] ) ) {
803 $tag = $tags_list[ self::$tag_map[ $tag ] ];
810 $value = translate( $value, $this->get('TextDomain') );
816 * The directory name of the theme's "stylesheet" files, inside the theme root.
818 * In the case of a child theme, this is directory name of the child theme.
819 * Otherwise, get_stylesheet() is the same as get_template().
824 * @return string Stylesheet
826 public function get_stylesheet() {
827 return $this->stylesheet;
831 * The directory name of the theme's "template" files, inside the theme root.
833 * In the case of a child theme, this is the directory name of the parent theme.
834 * Otherwise, the get_template() is the same as get_stylesheet().
839 * @return string Template
841 public function get_template() {
842 return $this->template;
846 * Returns the absolute path to the directory of a theme's "stylesheet" files.
848 * In the case of a child theme, this is the absolute path to the directory
849 * of the child theme's files.
854 * @return string Absolute path of the stylesheet directory.
856 public function get_stylesheet_directory() {
857 if ( $this->errors() && in_array( 'theme_root_missing', $this->errors()->get_error_codes() ) )
860 return $this->theme_root . '/' . $this->stylesheet;
864 * Returns the absolute path to the directory of a theme's "template" files.
866 * In the case of a child theme, this is the absolute path to the directory
867 * of the parent theme's files.
872 * @return string Absolute path of the template directory.
874 public function get_template_directory() {
875 if ( $this->parent() )
876 $theme_root = $this->parent()->theme_root;
878 $theme_root = $this->theme_root;
880 return $theme_root . '/' . $this->template;
884 * Returns the URL to the directory of a theme's "stylesheet" files.
886 * In the case of a child theme, this is the URL to the directory of the
887 * child theme's files.
892 * @return string URL to the stylesheet directory.
894 public function get_stylesheet_directory_uri() {
895 return $this->get_theme_root_uri() . '/' . str_replace( '%2F', '/', rawurlencode( $this->stylesheet ) );
899 * Returns the URL to the directory of a theme's "template" files.
901 * In the case of a child theme, this is the URL to the directory of the
902 * parent theme's files.
907 * @return string URL to the template directory.
909 public function get_template_directory_uri() {
910 if ( $this->parent() )
911 $theme_root_uri = $this->parent()->get_theme_root_uri();
913 $theme_root_uri = $this->get_theme_root_uri();
915 return $theme_root_uri . '/' . str_replace( '%2F', '/', rawurlencode( $this->template ) );
919 * The absolute path to the directory of the theme root.
921 * This is typically the absolute path to wp-content/themes.
926 * @return string Theme root.
928 public function get_theme_root() {
929 return $this->theme_root;
933 * Returns the URL to the directory of the theme root.
935 * This is typically the absolute URL to wp-content/themes. This forms the basis
936 * for all other URLs returned by WP_Theme, so we pass it to the public function
937 * get_theme_root_uri() and allow it to run the {@see 'theme_root_uri'} filter.
942 * @return string Theme root URI.
944 public function get_theme_root_uri() {
945 if ( ! isset( $this->theme_root_uri ) )
946 $this->theme_root_uri = get_theme_root_uri( $this->stylesheet, $this->theme_root );
947 return $this->theme_root_uri;
951 * Returns the main screenshot file for the theme.
953 * The main screenshot is called screenshot.png. gif and jpg extensions are also allowed.
955 * Screenshots for a theme must be in the stylesheet directory. (In the case of child
956 * themes, parent theme screenshots are not inherited.)
961 * @param string $uri Type of URL to return, either 'relative' or an absolute URI. Defaults to absolute URI.
962 * @return string|false Screenshot file. False if the theme does not have a screenshot.
964 public function get_screenshot( $uri = 'uri' ) {
965 $screenshot = $this->cache_get( 'screenshot' );
967 if ( 'relative' == $uri )
969 return $this->get_stylesheet_directory_uri() . '/' . $screenshot;
970 } elseif ( 0 === $screenshot ) {
974 foreach ( array( 'png', 'gif', 'jpg', 'jpeg' ) as $ext ) {
975 if ( file_exists( $this->get_stylesheet_directory() . "/screenshot.$ext" ) ) {
976 $this->cache_add( 'screenshot', 'screenshot.' . $ext );
977 if ( 'relative' == $uri )
978 return 'screenshot.' . $ext;
979 return $this->get_stylesheet_directory_uri() . '/' . 'screenshot.' . $ext;
983 $this->cache_add( 'screenshot', 0 );
988 * Return files in the theme's directory.
993 * @param mixed $type Optional. Array of extensions to return. Defaults to all files (null).
994 * @param int $depth Optional. How deep to search for files. Defaults to a flat scan (0 depth). -1 depth is infinite.
995 * @param bool $search_parent Optional. Whether to return parent files. Defaults to false.
996 * @return array Array of files, keyed by the path to the file relative to the theme's directory, with the values
997 * being absolute paths.
999 public function get_files( $type = null, $depth = 0, $search_parent = false ) {
1000 $files = (array) self::scandir( $this->get_stylesheet_directory(), $type, $depth );
1002 if ( $search_parent && $this->parent() )
1003 $files += (array) self::scandir( $this->get_template_directory(), $type, $depth );
1009 * Returns the theme's post templates.
1014 * @return array Array of page templates, keyed by filename and post type,
1015 * with the value of the translated header name.
1017 public function get_post_templates() {
1018 // If you screw up your current theme and we invalidate your parent, most things still work. Let it slide.
1019 if ( $this->errors() && $this->errors()->get_error_codes() !== array( 'theme_parent_invalid' ) ) {
1023 $post_templates = $this->cache_get( 'post_templates' );
1025 if ( ! is_array( $post_templates ) ) {
1026 $post_templates = array();
1028 $files = (array) $this->get_files( 'php', 1 );
1030 foreach ( $files as $file => $full_path ) {
1031 if ( ! preg_match( '|Template Name:(.*)$|mi', file_get_contents( $full_path ), $header ) ) {
1035 $types = array( 'page' );
1036 if ( preg_match( '|Template Post Type:(.*)$|mi', file_get_contents( $full_path ), $type ) ) {
1037 $types = explode( ',', _cleanup_header_comment( $type[1] ) );
1040 foreach ( $types as $type ) {
1041 $type = sanitize_key( $type );
1042 if ( ! isset( $post_templates[ $type ] ) ) {
1043 $post_templates[ $type ] = array();
1046 $post_templates[ $type ][ $file ] = _cleanup_header_comment( $header[1] );
1050 $this->cache_add( 'post_templates', $post_templates );
1053 if ( $this->load_textdomain() ) {
1054 foreach ( $post_templates as &$post_type ) {
1055 foreach ( $post_type as &$post_template ) {
1056 $post_template = $this->translate_header( 'Template Name', $post_template );
1061 return $post_templates;
1065 * Returns the theme's post templates for a given post type.
1068 * @since 4.7.0 Added the `$post_type` parameter.
1071 * @param WP_Post|null $post Optional. The post being edited, provided for context.
1072 * @param string $post_type Optional. Post type to get the templates for. Default 'page'.
1073 * If a post is provided, its post type is used.
1074 * @return array Array of page templates, keyed by filename, with the value of the translated header name.
1076 public function get_page_templates( $post = null, $post_type = 'page' ) {
1078 $post_type = get_post_type( $post );
1081 $post_templates = $this->get_post_templates();
1082 $post_templates = isset( $post_templates[ $post_type ] ) ? $post_templates[ $post_type ] : array();
1084 if ( $this->parent() ) {
1085 $post_templates += $this->parent()->get_page_templates( $post, $post_type );
1089 * Filters list of page templates for a theme.
1091 * The dynamic portion of the hook name, `$post_type`, refers to the post type.
1094 * @since 4.4.0 Converted to allow complete control over the `$page_templates` array.
1095 * @since 4.7.0 Added the `$post_type` parameter.
1097 * @param array $post_templates Array of page templates. Keys are filenames,
1098 * values are translated names.
1099 * @param WP_Theme $this The theme object.
1100 * @param WP_Post|null $post The post being edited, provided for context, or null.
1101 * @param string $post_type Post type to get the templates for.
1103 return (array) apply_filters( "theme_{$post_type}_templates", $post_templates, $this, $post, $post_type );
1107 * Scans a directory for files of a certain extension.
1114 * @param string $path Absolute path to search.
1115 * @param array|string|null $extensions Optional. Array of extensions to find, string of a single extension,
1116 * or null for all extensions. Default null.
1117 * @param int $depth Optional. How many levels deep to search for files. Accepts 0, 1+, or
1118 * -1 (infinite depth). Default 0.
1119 * @param string $relative_path Optional. The basename of the absolute path. Used to control the
1120 * returned path for the found files, particularly when this function
1121 * recurses to lower depths. Default empty.
1122 * @return array|false Array of files, keyed by the path to the file relative to the `$path` directory prepended
1123 * with `$relative_path`, with the values being absolute paths. False otherwise.
1125 private static function scandir( $path, $extensions = null, $depth = 0, $relative_path = '' ) {
1126 if ( ! is_dir( $path ) )
1129 if ( $extensions ) {
1130 $extensions = (array) $extensions;
1131 $_extensions = implode( '|', $extensions );
1134 $relative_path = trailingslashit( $relative_path );
1135 if ( '/' == $relative_path )
1136 $relative_path = '';
1138 $results = scandir( $path );
1141 foreach ( $results as $result ) {
1142 if ( '.' == $result[0] )
1144 if ( is_dir( $path . '/' . $result ) ) {
1145 if ( ! $depth || 'CVS' == $result )
1147 $found = self::scandir( $path . '/' . $result, $extensions, $depth - 1 , $relative_path . $result );
1148 $files = array_merge_recursive( $files, $found );
1149 } elseif ( ! $extensions || preg_match( '~\.(' . $_extensions . ')$~', $result ) ) {
1150 $files[ $relative_path . $result ] = $path . '/' . $result;
1158 * Loads the theme's textdomain.
1160 * Translation files are not inherited from the parent theme. Todo: if this fails for the
1161 * child theme, it should probably try to load the parent theme's translations.
1166 * @return bool True if the textdomain was successfully loaded or has already been loaded.
1167 * False if no textdomain was specified in the file headers, or if the domain could not be loaded.
1169 public function load_textdomain() {
1170 if ( isset( $this->textdomain_loaded ) )
1171 return $this->textdomain_loaded;
1173 $textdomain = $this->get('TextDomain');
1174 if ( ! $textdomain ) {
1175 $this->textdomain_loaded = false;
1179 if ( is_textdomain_loaded( $textdomain ) ) {
1180 $this->textdomain_loaded = true;
1184 $path = $this->get_stylesheet_directory();
1185 if ( $domainpath = $this->get('DomainPath') )
1186 $path .= $domainpath;
1188 $path .= '/languages';
1190 $this->textdomain_loaded = load_theme_textdomain( $textdomain, $path );
1191 return $this->textdomain_loaded;
1195 * Whether the theme is allowed (multisite only).
1200 * @param string $check Optional. Whether to check only the 'network'-wide settings, the 'site'
1201 * settings, or 'both'. Defaults to 'both'.
1202 * @param int $blog_id Optional. Ignored if only network-wide settings are checked. Defaults to current site.
1203 * @return bool Whether the theme is allowed for the network. Returns true in single-site.
1205 public function is_allowed( $check = 'both', $blog_id = null ) {
1206 if ( ! is_multisite() )
1209 if ( 'both' == $check || 'network' == $check ) {
1210 $allowed = self::get_allowed_on_network();
1211 if ( ! empty( $allowed[ $this->get_stylesheet() ] ) )
1215 if ( 'both' == $check || 'site' == $check ) {
1216 $allowed = self::get_allowed_on_site( $blog_id );
1217 if ( ! empty( $allowed[ $this->get_stylesheet() ] ) )
1225 * Determines the latest WordPress default theme that is installed.
1227 * This hits the filesystem.
1229 * @return WP_Theme|false Object, or false if no theme is installed, which would be bad.
1231 public static function get_core_default_theme() {
1232 foreach ( array_reverse( self::$default_themes ) as $slug => $name ) {
1233 $theme = wp_get_theme( $slug );
1234 if ( $theme->exists() ) {
1242 * Returns array of stylesheet names of themes allowed on the site or network.
1249 * @param int $blog_id Optional. ID of the site. Defaults to the current site.
1250 * @return array Array of stylesheet names.
1252 public static function get_allowed( $blog_id = null ) {
1254 * Filters the array of themes allowed on the network.
1256 * Site is provided as context so that a list of network allowed themes can
1257 * be filtered further.
1261 * @param array $allowed_themes An array of theme stylesheet names.
1262 * @param int $blog_id ID of the site.
1264 $network = (array) apply_filters( 'network_allowed_themes', self::get_allowed_on_network(), $blog_id );
1265 return $network + self::get_allowed_on_site( $blog_id );
1269 * Returns array of stylesheet names of themes allowed on the network.
1276 * @staticvar array $allowed_themes
1278 * @return array Array of stylesheet names.
1280 public static function get_allowed_on_network() {
1281 static $allowed_themes;
1282 if ( ! isset( $allowed_themes ) ) {
1283 $allowed_themes = (array) get_site_option( 'allowedthemes' );
1287 * Filters the array of themes allowed on the network.
1291 * @param array $allowed_themes An array of theme stylesheet names.
1293 $allowed_themes = apply_filters( 'allowed_themes', $allowed_themes );
1295 return $allowed_themes;
1299 * Returns array of stylesheet names of themes allowed on the site.
1306 * @staticvar array $allowed_themes
1308 * @param int $blog_id Optional. ID of the site. Defaults to the current site.
1309 * @return array Array of stylesheet names.
1311 public static function get_allowed_on_site( $blog_id = null ) {
1312 static $allowed_themes = array();
1314 if ( ! $blog_id || ! is_multisite() )
1315 $blog_id = get_current_blog_id();
1317 if ( isset( $allowed_themes[ $blog_id ] ) ) {
1319 * Filters the array of themes allowed on the site.
1323 * @param array $allowed_themes An array of theme stylesheet names.
1324 * @param int $blog_id ID of the site. Defaults to current site.
1326 return (array) apply_filters( 'site_allowed_themes', $allowed_themes[ $blog_id ], $blog_id );
1329 $current = $blog_id == get_current_blog_id();
1332 $allowed_themes[ $blog_id ] = get_option( 'allowedthemes' );
1334 switch_to_blog( $blog_id );
1335 $allowed_themes[ $blog_id ] = get_option( 'allowedthemes' );
1336 restore_current_blog();
1339 // This is all super old MU back compat joy.
1340 // 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
1341 if ( false === $allowed_themes[ $blog_id ] ) {
1343 $allowed_themes[ $blog_id ] = get_option( 'allowed_themes' );
1345 switch_to_blog( $blog_id );
1346 $allowed_themes[ $blog_id ] = get_option( 'allowed_themes' );
1347 restore_current_blog();
1350 if ( ! is_array( $allowed_themes[ $blog_id ] ) || empty( $allowed_themes[ $blog_id ] ) ) {
1351 $allowed_themes[ $blog_id ] = array();
1353 $converted = array();
1354 $themes = wp_get_themes();
1355 foreach ( $themes as $stylesheet => $theme_data ) {
1356 if ( isset( $allowed_themes[ $blog_id ][ $theme_data->get('Name') ] ) )
1357 $converted[ $stylesheet ] = true;
1359 $allowed_themes[ $blog_id ] = $converted;
1361 // Set the option so we never have to go through this pain again.
1362 if ( is_admin() && $allowed_themes[ $blog_id ] ) {
1364 update_option( 'allowedthemes', $allowed_themes[ $blog_id ] );
1365 delete_option( 'allowed_themes' );
1367 switch_to_blog( $blog_id );
1368 update_option( 'allowedthemes', $allowed_themes[ $blog_id ] );
1369 delete_option( 'allowed_themes' );
1370 restore_current_blog();
1375 /** This filter is documented in wp-includes/class-wp-theme.php */
1376 return (array) apply_filters( 'site_allowed_themes', $allowed_themes[ $blog_id ], $blog_id );
1380 * Enables a theme for all sites on the current network.
1386 * @param string|array $stylesheets Stylesheet name or array of stylesheet names.
1388 public static function network_enable_theme( $stylesheets ) {
1389 if ( ! is_multisite() ) {
1393 if ( ! is_array( $stylesheets ) ) {
1394 $stylesheets = array( $stylesheets );
1397 $allowed_themes = get_site_option( 'allowedthemes' );
1398 foreach ( $stylesheets as $stylesheet ) {
1399 $allowed_themes[ $stylesheet ] = true;
1402 update_site_option( 'allowedthemes', $allowed_themes );
1406 * Disables a theme for all sites on the current network.
1412 * @param string|array $stylesheets Stylesheet name or array of stylesheet names.
1414 public static function network_disable_theme( $stylesheets ) {
1415 if ( ! is_multisite() ) {
1419 if ( ! is_array( $stylesheets ) ) {
1420 $stylesheets = array( $stylesheets );
1423 $allowed_themes = get_site_option( 'allowedthemes' );
1424 foreach ( $stylesheets as $stylesheet ) {
1425 if ( isset( $allowed_themes[ $stylesheet ] ) ) {
1426 unset( $allowed_themes[ $stylesheet ] );
1430 update_site_option( 'allowedthemes', $allowed_themes );
1434 * Sorts themes by name.
1441 * @param array $themes Array of themes to sort, passed by reference.
1443 public static function sort_by_name( &$themes ) {
1444 if ( 0 === strpos( get_user_locale(), 'en_' ) ) {
1445 uasort( $themes, array( 'WP_Theme', '_name_sort' ) );
1447 uasort( $themes, array( 'WP_Theme', '_name_sort_i18n' ) );
1452 * Callback function for usort() to naturally sort themes by name.
1454 * Accesses the Name header directly from the class for maximum speed.
1455 * Would choke on HTML but we don't care enough to slow it down with strip_tags().
1462 * @param string $a First name.
1463 * @param string $b Second name.
1464 * @return int Negative if `$a` falls lower in the natural order than `$b`. Zero if they fall equally.
1465 * Greater than 0 if `$a` falls higher in the natural order than `$b`. Used with usort().
1467 private static function _name_sort( $a, $b ) {
1468 return strnatcasecmp( $a->headers['Name'], $b->headers['Name'] );
1472 * Name sort (with translation).
1479 * @param string $a First name.
1480 * @param string $b Second name.
1481 * @return int Negative if `$a` falls lower in the natural order than `$b`. Zero if they fall equally.
1482 * Greater than 0 if `$a` falls higher in the natural order than `$b`. Used with usort().
1484 private static function _name_sort_i18n( $a, $b ) {
1485 // Don't mark up; Do translate.
1486 return strnatcasecmp( $a->display( 'Name', false, true ), $b->display( 'Name', false, true ) );