WP_Theme::get_post_templates() WordPress Method

The WP_Theme::get_post_templates() method is used to retrieve an array of all available post templates for the current theme. This can be useful for creating a custom post template selector for the front-end of your website.

WP_Theme::get_post_templates() #

Returns the theme’s post templates.


Return

(array[]) Array of page template arrays, keyed by post type and filename, with the value of the translated header name.


Top ↑

Source

File: wp-includes/class-wp-theme.php

	public function get_post_templates() {
		// If you screw up your active theme and we invalidate your parent, most things still work. Let it slide.
		if ( $this->errors() && $this->errors()->get_error_codes() !== array( 'theme_parent_invalid' ) ) {
			return array();
		}

		$post_templates = $this->cache_get( 'post_templates' );

		if ( ! is_array( $post_templates ) ) {
			$post_templates = array();

			$files = (array) $this->get_files( 'php', 1, true );

			foreach ( $files as $file => $full_path ) {
				if ( ! preg_match( '|Template Name:(.*)$|mi', file_get_contents( $full_path ), $header ) ) {
					continue;
				}

				$types = array( 'page' );
				if ( preg_match( '|Template Post Type:(.*)$|mi', file_get_contents( $full_path ), $type ) ) {
					$types = explode( ',', _cleanup_header_comment( $type[1] ) );
				}

				foreach ( $types as $type ) {
					$type = sanitize_key( $type );
					if ( ! isset( $post_templates[ $type ] ) ) {
						$post_templates[ $type ] = array();
					}

					$post_templates[ $type ][ $file ] = _cleanup_header_comment( $header[1] );
				}
			}

			if ( current_theme_supports( 'block-templates' ) ) {
				$block_templates = get_block_templates( array(), 'wp_template' );
				foreach ( get_post_types( array( 'public' => true ) ) as $type ) {
					foreach ( $block_templates as $block_template ) {
						if ( ! $block_template->is_custom ) {
							continue;
						}

						if ( isset( $block_template->post_types ) && ! in_array( $type, $block_template->post_types, true ) ) {
							continue;
						}

						$post_templates[ $type ][ $block_template->slug ] = $block_template->title;
					}
				}
			}

			$this->cache_add( 'post_templates', $post_templates );
		}

		if ( $this->load_textdomain() ) {
			foreach ( $post_templates as &$post_type ) {
				foreach ( $post_type as &$post_template ) {
					$post_template = $this->translate_header( 'Template Name', $post_template );
				}
			}
		}

		return $post_templates;
	}


Top ↑

Changelog

Changelog
VersionDescription
5.8.0Include block templates.
4.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.