wpseek.com
A WordPress-centric search engine for devs and theme authors



get_template_hierarchy › WordPress Function

Since6.1.0
Deprecatedn/a
get_template_hierarchy ( $slug, $is_custom = false, $template_prefix = '' )
Parameters: (3)
  • (string) $slug The template slug to be created.
    Required: Yes
  • (bool) $is_custom Optional. Indicates if a template is custom or part of the template hierarchy. Default false.
    Required: No
    Default: false
  • (string) $template_prefix Optional. The template prefix for the created template. Used to extract the main template type, e.g. in `taxonomy-books` the `taxonomy` is extracted. Default empty string.
    Required: No
    Default: (empty)
Returns:
  • (string[]) The template hierarchy.
Defined at:
Codex:

Gets the template hierarchy for the given template slug to be created.

Note: Always add index as the last fallback template.


Source

function get_template_hierarchy( $slug, $is_custom = false, $template_prefix = '' ) {
	if ( 'index' === $slug ) {
		return array( 'index' );
	}
	if ( $is_custom ) {
		return array( 'page', 'singular', 'index' );
	}
	if ( 'front-page' === $slug ) {
		return array( 'front-page', 'home', 'index' );
	}

	$template_hierarchy = array( $slug );

	// Most default templates don't have `$template_prefix` assigned.
	if ( $template_prefix ) {
		list( $type ) = explode( '-', $template_prefix );
		// These checks are needed because the `$slug` above is always added.
		if ( ! in_array( $template_prefix, array( $slug, $type ), true ) ) {
			$template_hierarchy[] = $template_prefix;
		}
		if ( $slug !== $type ) {
			$template_hierarchy[] = $type;
		}
	}

	// Handle `archive` template.
	if (
		str_starts_with( $slug, 'author' ) ||
		str_starts_with( $slug, 'taxonomy' ) ||
		str_starts_with( $slug, 'category' ) ||
		str_starts_with( $slug, 'tag' ) ||
		'date' === $slug
	) {
		$template_hierarchy[] = 'archive';
	}
	// Handle `single` template.
	if ( 'attachment' === $slug ) {
		$template_hierarchy[] = 'single';
	}

	// Handle `singular` template.
	if (
		str_starts_with( $slug, 'single' ) ||
		str_starts_with( $slug, 'page' ) ||
		'attachment' === $slug
	) {
		$template_hierarchy[] = 'singular';
	}

	$template_hierarchy[] = 'index';

	return $template_hierarchy;
};