diff --git a/src/wp-includes/template.php b/src/wp-includes/template.php index 401df4db19925..d07296045ca85 100644 --- a/src/wp-includes/template.php +++ b/src/wp-includes/template.php @@ -729,15 +729,18 @@ function locate_template( $template_names, $load = false, $load_once = true, $ar if ( ! $template_name ) { continue; } - if ( file_exists( $wp_stylesheet_path . '/' . $template_name ) ) { - $located = $wp_stylesheet_path . '/' . $template_name; - break; - } elseif ( $is_child_theme && file_exists( $wp_template_path . '/' . $template_name ) ) { - $located = $wp_template_path . '/' . $template_name; + $stylesheet = $wp_stylesheet_path . '/' . $template_name; + $template = $wp_template_path . '/' . $template_name; + $template_compat = ABSPATH . WPINC . '/theme-compat/' . $template_name; + + if ( file_exists( $stylesheet ) && 0 === validate_file( $stylesheet ) ) { + $located = $stylesheet; break; - } elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) { - $located = ABSPATH . WPINC . '/theme-compat/' . $template_name; + } elseif ( $is_child_theme && file_exists( $template ) && 0 === validate_file( $template ) ) { + $located = $template; break; + } elseif ( file_exists( $template_compat ) && 0 === validate_file( $template_compat ) ) { + $located = $template_compat; } } diff --git a/tests/phpunit/tests/template.php b/tests/phpunit/tests/template.php index 0507be4327250..717a76b4aade7 100644 --- a/tests/phpunit/tests/template.php +++ b/tests/phpunit/tests/template.php @@ -494,6 +494,45 @@ public function test_locate_template_uses_current_theme() { $this->assertSame( $new_theme->get_stylesheet_directory() . '/index.php', locate_template( $template_names ), 'Incorrect index template found in theme after switch.' ); } + /** + * Tests that `locate_template()` uses the current theme even after switching the theme. + * + * @dataProvider data_locate_template_only_loads_theme_files + * + * @ticket 58905 + * + * @covers ::locate_template + * + * @param string $template_name Template name to locate. + * @param bool $located_empty Whether the located template should be empty. + */ + public function test_locate_template_only_loads_theme_files( $template_name, $located_empty ) { + $located_return = locate_template( $template_name ); + $this->assertSame( empty( $located_return ), $located_empty ); + } + + /** + * Data provider for `test_locate_template_only_loads_theme_files()`. + * + * @return array + */ + public function data_locate_template_only_loads_theme_files() { + return array( + 'file that is in theme compat so will always return' => array( + 'header.php', + false, + ), + 'something that does not exist' => array( + 'the_limit_according_to_cady_heron.php', + true, + ), + 'file that is not in a theme path' => array( + WP_PLUGIN_DIR . '/hello.php', + true, + ), + ); + } + public function assertTemplateHierarchy( $url, array $expected, $message = '' ) { $this->go_to( $url ); $hierarchy = $this->get_template_hierarchy();