the_title
云策文档标注
概述
the_title 是一个 WordPress 过滤器,用于在从数据库检索文章标题并显示到屏幕之前对其进行修改。开发者可以通过此过滤器动态调整标题内容,例如基于特定条件抑制标题或格式化标题。
关键要点
- the_title 过滤器允许修改文章标题,参数包括 $post_title(字符串)和 $post_id(整数)。
- 在某些情况下(如使用 the_title 时),可以通过返回 false 值(如 NULL、FALSE 或空字符串)来抑制标题显示。
- 该过滤器在 WordPress 0.71 版本中引入,广泛用于多种核心功能,如 REST API、自定义菜单和文章列表。
代码示例
// 示例1:抑制特定分类下的文章标题
function suppress_if_blurb( $title, $id = null ) {
if ( in_category('blurb', $id ) ) {
return '';
}
return $title;
}
add_filter( 'the_title', 'suppress_if_blurb', 10, 2 );
// 示例2:将标题转换为大写
add_filter( 'the_title', 'wpdocs_capitalise_post_titles' );
function wpdocs_capitalise_post_titles( $title ) {
return ucwords( $title );
}注意事项
- 在 WordPress 3.1 至 3.2 版本中,the_title 过滤器在某些使用场景下可能未提供 $post_id 参数,导致不一致性。为兼容这些旧版本,建议在回调函数中为 $id 参数设置默认值(如 null),以避免 PHP 警告。
- 如果不需要支持 3.1 或 3.2 版本,则无需为 $id 指定默认值。
原文内容
Filters the post title.
Parameters
$post_titlestring-
The post title.
$post_idint-
The post ID.
Source
return apply_filters( 'the_title', $post_title, $post_id );
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |
Skip to note 3 content
Steven Lin
Suppressing the title in templates for all posts in the “blurb” category:
function suppress_if_blurb( $title, $id = null ) { if ( in_category(' blurb', $id ) ) { return ''; } return $title; } add_filter( 'the_title', 'suppress_if_blurb', 10, 2 );Note the addition of
nullas the default value for the$idvariable. This is because some instances of the usage of this filter did not supply a post ID. This inconsistency was introduced in version 3.1, and fixed in version 3.3 (see ticket #16688). If you want to be compatible with these older versions, you need to supply the default value as above, or you will end up with a PHP warning stating that you are missing an argument. If you don’t need to support 3.1 or 3.2, it isn’t necessary to specify a default value for$id.Skip to note 4 content
Chigozie Orunta
Render capitalised post titles across your site like so:
add_filter( 'the_title', 'wpdocs_capitalise_post_titles' ); function wpdocs_capitalise_post_titles( $title ) { return ucwords( $title ); }