函数文档

get_single_template()

💡 云策文档标注

概述

get_single_template() 函数用于检索当前或父模板中单篇内容模板的路径,适用于单篇文章、附件和自定义文章类型。它基于模板层级结构查找模板文件,并返回完整路径。

关键要点

  • 函数返回单篇内容模板文件的完整路径字符串。
  • 模板层级结构包括:{Post Type Template}.php、single-{post_type}-{post_name}.php、single-{post_type}.php、single.php。
  • 可通过动态钩子 '$type_template_hierarchy' 和 '$type_template'($type 为 'single')过滤模板层级和路径。
  • 内部使用 get_query_template() 函数来检索模板。
  • 相关函数包括 get_queried_object()、validate_file()、get_page_template_slug()。

代码示例

function get_single_template() {
    $object = get_queried_object();

    $templates = array();

    if ( ! empty( $object->post_type ) ) {
        $template = get_page_template_slug( $object );
        if ( $template && 0 === validate_file( $template ) ) {
            $templates[] = $template;
        }

        $name_decoded = urldecode( $object->post_name );
        if ( $name_decoded !== $object->post_name ) {
            $templates[] = "single-{$object->post_type}-{$name_decoded}.php";
        }

        $templates[] = "single-{$object->post_type}-{$object->post_name}.php";
        $templates[] = "single-{$object->post_type}.php";
    }

    $templates[] = 'single.php';

    return get_query_template( 'single', $templates );
}

注意事项

  • 从 WordPress 4.7.0 开始,{Post Type Template}.php 被添加到模板层级结构的顶部。
  • 从 WordPress 4.4.0 开始,single-{post_type}-{post_name}.php 被添加到模板层级结构的顶部。
  • 函数自 WordPress 1.5.0 引入。

📄 原文内容

Retrieves path of single template in current or parent template. Applies to single Posts, single Attachments, and single custom post types.

Description

The hierarchy for this template looks like:

  1. {Post Type Template}.php
  2. single-{post_type}-{post_name}.php
  3. single-{post_type}.php
  4. single.php

An example of this is:

  1. templates/full-width.php
  2. single-post-hello-world.php
  3. single-post.php
  4. single.php

The template hierarchy and template path are filterable via the ‘$type_template_hierarchy’ and ‘$type_template’ dynamic hooks, where $type is ‘single’.

See also

Return

string Full path to single template file.

Source

function get_single_template() {
	$object = get_queried_object();

	$templates = array();

	if ( ! empty( $object->post_type ) ) {
		$template = get_page_template_slug( $object );
		if ( $template && 0 === validate_file( $template ) ) {
			$templates[] = $template;
		}

		$name_decoded = urldecode( $object->post_name );
		if ( $name_decoded !== $object->post_name ) {
			$templates[] = "single-{$object->post_type}-{$name_decoded}.php";
		}

		$templates[] = "single-{$object->post_type}-{$object->post_name}.php";
		$templates[] = "single-{$object->post_type}.php";
	}

	$templates[] = 'single.php';

	return get_query_template( 'single', $templates );
}

Changelog

Version Description
4.7.0 {Post Type Template}.php was added to the top of the template hierarchy.
4.4.0 single-{post_type}-{post_name}.php was added to the top of the template hierarchy.
1.5.0 Introduced.