Using WordPress ‘get_page_templates()’ PHP function

The get_page_templates() WordPress PHP function retrieves the page templates available in the current theme.

Usage

To get a list of available page templates:

$templates = get_page_templates();
print_r($templates);

Output:

Array (
  [template-contact.php] => Contact
  [template-landing-page.php] => Landing Page
  [template-another-template.php] => Another Template
)

Parameters

  • $post (WP_Post|null) (optional) – The post being edited, provided for context. Default: null.
  • $post_type (string) (optional) – Post type to get the templates for. Default: ‘page’.

More information

See WordPress Developer Resources: get_page_templates

Examples

Display a dropdown list of available templates

This code snippet creates a dropdown list containing available page templates.

$templates = get_page_templates();

echo '<select>';
foreach ($templates as $template_file => $template_name) {
    echo '<option value="' . $template_file . '">' . $template_name . '</option>';
}
echo '</select>';

Filter page templates by a specific keyword

This code snippet filters the page templates that include the keyword ‘landing’ in their name.

$templates = get_page_templates();
$filtered_templates = array_filter($templates, function ($template_name) {
    return strpos(strtolower($template_name), 'landing') !== false;
});

print_r($filtered_templates);

Get page templates for a custom post type

This code snippet retrieves the page templates available for a custom post type called ‘product’.

$custom_post_type = 'product';
$templates = get_page_templates(null, $custom_post_type);

print_r($templates);

Add a prefix to the template names

This code snippet adds a prefix ‘Custom – ‘ to the template names.

$templates = get_page_templates();
$prefixed_templates = array_map(function ($template_name) {
    return 'Custom - ' . $template_name;
}, $templates);

print_r($prefixed_templates);

Sort templates alphabetically by name

This code snippet sorts the templates alphabetically by their names.

$templates = get_page_templates();
asort($templates);

print_r($templates);