Wordpress Snippets

Get A List Of All Custom Page Templates in WordPress

Pages are one of WordPress’s built-in Post Types. You’ll probably want most of your website Pages to look about the same. But sometimes, though, you may need a specific Page, or a group of Pages, to display or behave differently. This is easily accomplished with custom Page Templates. WordPress allows you to create custom page templates to use throughout your site, using these custom page templates you can completely change the look and functionality of a certain page.

If you are developing something for WordPress and need to get a list of all custom page templates that currently exist on the WordPress theme then you can use the following code snippet. This WordPress code snippet returns all the custom Page Templates available to the currently activated WordPress theme as an array. Each array item has a key of the Template Name and value of the filename (or folder-name and filename for custom page templates stored in a theme’s subdirectory). What it actually does is, it searches all the current theme’s template files for the commented “Template Name: name of template” and returns in an array for further uses.

You can use this method in your theme files to get a list of all custom page templates in currently activated WordPress theme.

<?php

    // get a list of all custom page templates in wordpress
    $themeObj = wp_get_theme();
    $templates = $themeObj->get_page_templates();

    echo "<ul>";
    foreach ( $templates as $template_name => $template_filename ) {
        echo "<li>" . $template_name . "(" . $template_filename . ")</li>";
    }
    echo "</ul>";

?>

Hire Us. Or just say Hi!
Need a job? Apply to get one.