Using WordPress ‘page_template_dropdown()’ PHP function

The page_template_dropdown() WordPress PHP function prints out option HTML elements for the page templates drop-down.

Usage

page_template_dropdown($default_template, $post_type);

Parameters

  • $default_template (string) – Optional. The template file name. Default: ''.
  • $post_type (string) – Optional. Post type to get templates for. Default: 'page'.

More information

See WordPress Developer Resources: page_template_dropdown()

Examples

Displaying a drop-down of page templates

This code snippet creates a drop-down list of available page templates.

// Display a drop-down of page templates
page_template_dropdown();

Setting a default selected template

This code snippet creates a drop-down list of available page templates with a default selected template.

// Set a default selected template
page_template_dropdown('custom-template.php');

Displaying templates for a custom post type

This code snippet displays a drop-down list of available page templates for a custom post type.

// Display templates for a custom post type
page_template_dropdown('', 'custom_post_type');

Using the drop-down inside a form

This code snippet demonstrates how to use the page_template_dropdown() function inside an HTML form.

<form action="" method="post">
  <label for="template">Select a template:</label>
  <?php
  // Display the drop-down list of templates
  page_template_dropdown();
  ?>
  <input type="submit" value="Choose">
</form>

Filtering the drop-down options

This code snippet filters the drop-down options to display only templates with a specific prefix.

// Add a filter to show only templates with a specific prefix
function my_prefix_filter($templates) {
  $filtered = array();
  $prefix = 'my_prefix-';

  foreach ($templates as $key => $value) {
    if (strpos($value, $prefix) === 0) {
      $filtered[$key] = $value;
    }
  }

  return $filtered;
}
add_filter('page_templates', 'my_prefix_filter');

// Display the filtered drop-down list
page_template_dropdown();