PHP has a function, get_included_files()
, that returns all the files that have been included during a request.
However, if you use that function you obtain all the files required: WordPress core files, plugin files…
You need a way to:
- Filter out files that do not belong to the theme and child theme (if any)
- Include only files loaded after the main template has been included
Also you need to call this function as late as possible; shutdown
would be the better hook, however, wp_footer
should be fine, because it’s rare that you include a file after that hook has been fired.
Regarding the 2 problems mentioned above, the first can be solved by filtering the array for files that only belong to the theme folder.
The second can be solved by using template_include
, with a very low priority, to save the path of the main template, and then including in the output only files included after it.
Here’s a class that implements what’s said above. Put in a file and require from functions.php
:
class IncludedPartGrabber
{
private $main;
private $root;
private $switch = false;
public function setup( $template )
{
$this->root = wp_normalize_path( get_theme_root() ); // theme folder
$this->main = wp_normalize_path( $template ); // main template
return $template;
}
public function grab()
{
return array_filter( get_included_files(), array( $this, 'filter' ) );
}
private function filter( $file )
{
$norm = wp_normalize_path( $file );
if ( $norm === $this->main )
$this->switch = TRUE; // after main template all files are good to be included
return $this->switch && strpos( $norm, $this->root ) === 0; // true if file is in theme dir
}
}
Use it like so, in your functions.php
:
$grabber = new IncludedPartGrabber;
add_action( 'template_include', array( $grabber, 'setup' ) );
add_action( 'wp_footer', function() use($grabber) {
echo '<pre>';
print_r( $grabber->grab() ); // see your footer :)
echo '</pre>';
} );
If you want to use inside a template file, in functions.php
put:
global $grabber;
$grabber = new IncludedPartGrabber;
add_action( 'template_include', array( $grabber, 'setup' ) );
and then in the template file, e.g. footer.php
:
<pre><?php print_r( $GLOBALS['grabber']->grab() ); ?></pre>
Of course you can use in header.php
too, but from that file you’ll get only the files loaded at the moment header.php
has been included, e.g. page.php
and header.php
. PHP is a programming language, not a magic machine, and can’t know which files are going to be included before they are actually included.