The code below will list the names of the PHP template files not used on your website that still exist in your WordPress theme.

This might be a good way to find out what it’s extra when you’re refactoring or dealing with an old project that needs a revamp.

<?php 
    $templates = wp_get_theme()->get_page_templates();
    $template_list = [];

    foreach ($templates as $key => $template) {
        $template_list[] = $key;
    }

    $args = array(
        'post_type' => 'page',
        'posts_per_page' => -1
    ); 

    $the_query = new WP_Query( $args );
    $pages = $the_query->query($args);
    $used_templates_list = [];
    
    foreach ($pages as $key => $page) {
        $used_templates_list[] = get_page_template_slug($page->ID);
    }

    $used_templates_list = array_filter($used_templates_list);
    $unused_templates = array_diff($template_list, $used_templates_list);

    echo '<pre>';
    print_r($unused_templates);
    echo '</pre>';
?>

Topics: WordPress