document_title_parts
云策文档标注
概述
document_title_parts 是一个 WordPress 过滤器,用于修改文档标题的各个部分。它允许开发者通过 add_filter 函数自定义标题内容,例如针对特定页面或条件调整标题。
关键要点
- 过滤器名称:document_title_parts,用于过滤文档标题的组成部分。
- 参数:$title 是一个数组,包含 title(页面标题)、page(页码)、tagline(站点描述)和 site(站点标题)等键。
- 用法:通过 apply_filters('document_title_parts', $title) 调用,开发者可以添加过滤器来修改 $title 数组。
- 相关函数:与 wp_get_document_title() 关联,用于获取当前页面的文档标题。
- 版本:从 WordPress 4.4.0 开始引入。
代码示例
add_filter( 'document_title_parts', function( $title_parts_array ) {
if ( get_the_ID() == 2055 ) {
$title_parts_array['title'] = 'Custom Page Title';
}
return $title_parts_array;
} );注意事项
- 在模板文件中使用 add_filter() 时,应确保它在 get_header() 之前调用,以避免过滤器不生效。
- 建议将 add_filter() 调用放在主题的 functions.php 文件中,而不是模板文件,以遵循最佳实践。
原文内容
Filters the parts of the document title.
Parameters
$titlearray-
The document title parts.
titlestringTitle of the viewed page.pagestringOptional. Page number if paginated.taglinestringOptional. Site description when on home page.sitestringOptional. Site title when not on home page.
Source
$title = apply_filters( 'document_title_parts', $title );
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |
Skip to note 3 content
Dave Navarro, Jr.
Change the title for a specific page ID:
add_filter( 'document_title_parts', function( $title_parts_array ) { if ( get_the_ID() == 2055 ) { $title_parts_array['title'] = 'Custom Page Title'; } return $title_parts_array; } );Skip to note 4 content
coreytrice
Make sure your add_filter() comes before the get_header() in your template file if you adding a title filter for that template file.
</pre>in your template file. These kind of calls should live in your theme’s</div><!-- .comment-content -->
<section id='feedback-2886' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='1'>
<ul class='children'>
<li id="comment-2970" data-comment-id="2970" class="comment byuser comment-author-infostreams odd alt depth-2">
<article id="div-comment-2970" class="comment-body">
<div class="wporg-has-embedded-code comment-content" id="comment-content-2970">
<div>It’s bad practice to do <code>add_filter
functions.phpfile instead.