single_post_title()
云策文档标注
概述
single_post_title() 函数用于在 single.php 模板文件中显示或检索单篇文章的标题,针对单篇文章页面进行了优化。
关键要点
- 函数接受两个可选参数:$prefix(前缀字符串)和 $display(布尔值,控制显示或返回标题)。
- 默认行为是直接输出标题,若 $display 为 false 则返回标题字符串。
- 前缀不会自动添加空格,需在参数值中手动包含。
- 通过 apply_filters('single_post_title', ...) 钩子允许过滤标题。
- 相关函数包括 get_queried_object() 和 wp_title()。
代码示例
function single_post_title( $prefix = '', $display = true ) {
$_post = get_queried_object();
if ( ! isset( $_post->post_title ) ) {
return;
}
/**
* Filters the page title for a single post.
*
* @since 0.71
*
* @param string $_post_title The single post page title.
* @param WP_Post $_post The current post.
*/
$title = apply_filters( 'single_post_title', $_post->post_title, $_post );
if ( $display ) {
echo $prefix . $title;
} else {
return $prefix . $title;
}
}注意事项
- 此函数专为 single.php 设计,不支持在标题后自动添加分隔符。
- 前缀参数需手动处理空格,例如使用 $prefix = 'Prefix: ' 来确保正确格式。
原文内容
Displays or retrieves page title for post.
Description
This is optimized for single.php template file for displaying the post title.
It does not support placing the separator after the title, but by leaving the prefix parameter empty, you can set the title separator manually. The prefix does not automatically place a space between the prefix, so if there should be a space, the parameter value will need to have it at the end.
Parameters
$prefixstringoptional-
What to display before the title.
$displaybooloptional-
Whether to display or retrieve title.
Default:
true
Source
function single_post_title( $prefix = '', $display = true ) {
$_post = get_queried_object();
if ( ! isset( $_post->post_title ) ) {
return;
}
/**
* Filters the page title for a single post.
*
* @since 0.71
*
* @param string $_post_title The single post page title.
* @param WP_Post $_post The current post.
*/
$title = apply_filters( 'single_post_title', $_post->post_title, $_post );
if ( $display ) {
echo $prefix . $title;
} else {
return $prefix . $title;
}
}
Hooks
- apply_filters( ‘single_post_title’, string $_post_title, WP_Post $_post )
-
Filters the page title for a single post.
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |
Skip to note 2 content
Codex
Example
<h2></h2>Result:
Current post: Single Post Title