post_type_archive_title()
云策文档标注
概述
post_type_archive_title() 函数用于显示或检索自定义文章类型存档页面的标题。它专为 archive.php 和 archive-{$post_type}.php 模板文件优化,以输出文章类型的标签名称。
关键要点
- 函数接受两个可选参数:$prefix(标题前缀)和 $display(是否显示标题,默认为 true)。
- 返回值取决于 $display 参数:当 $display 为 false 时返回标题字符串,否则无返回值(直接输出)。
- 函数内部使用 get_post_type_object() 获取文章类型对象,并通过 apply_filters() 应用 'post_type_archive_title' 钩子进行过滤。
- 仅在 is_post_type_archive() 返回 true 时执行,否则直接返回。
代码示例
// 显示自定义文章类型存档标题,带前缀
post_type_archive_title( 'Archive: ', true );
// 检索标题而不显示,用于变量赋值
$title = post_type_archive_title( '', false );注意事项
- 确保在正确的存档页面上下文中调用此函数,否则可能无输出或返回空值。
- 可通过 'post_type_archive_title' 过滤器自定义标题输出。
原文内容
Displays or retrieves title for a post type archive.
Description
This is optimized for archive.php and archive-{$post_type}.php template files for displaying the title of the post type.
Parameters
$prefixstringoptional-
What to display before the title.
$displaybooloptional-
Whether to display or retrieve title.
Default:
true
Source
function post_type_archive_title( $prefix = '', $display = true ) {
if ( ! is_post_type_archive() ) {
return;
}
$post_type = get_query_var( 'post_type' );
if ( is_array( $post_type ) ) {
$post_type = reset( $post_type );
}
$post_type_obj = get_post_type_object( $post_type );
/**
* Filters the post type archive title.
*
* @since 3.1.0
*
* @param string $post_type_name Post type 'name' label.
* @param string $post_type Post type.
*/
$title = apply_filters( 'post_type_archive_title', $post_type_obj->labels->name, $post_type );
if ( $display ) {
echo $prefix . $title;
} else {
return $prefix . $title;
}
}
Hooks
- apply_filters( ‘post_type_archive_title’, string $post_type_name, string $post_type )
-
Filters the post type archive title.
Changelog
| Version | Description |
|---|---|
| 3.1.0 | Introduced. |
Skip to note 2 content
Codex
Display the Custom Post Type title:
<h1></h1>