钩子文档

pre_get_document_title

💡 云策文档标注

概述

pre_get_document_title 是一个 WordPress 过滤器钩子,用于在生成文档标题之前修改标题内容。传递非空值可以短路 wp_get_document_title() 函数,直接返回该值。

关键要点

  • 过滤器钩子:pre_get_document_title,在 wp_get_document_title() 执行前触发。
  • 参数:$title(字符串),文档标题,默认为空字符串。
  • 短路机制:如果过滤器返回非空值,将跳过默认标题生成过程。
  • 相关函数:wp_get_document_title(),用于获取当前页面的文档标题。
  • 版本:从 WordPress 4.4.0 开始引入。

代码示例

// 在首页或前台页面仅显示站点名称作为标题
function wporg_only_title_home_page( $title ) {
    if ( is_home() || is_front_page() ) {
        $title = get_bloginfo( 'name' );
    }
    return $title;
}
add_filter( 'pre_get_document_title', 'wporg_only_title_home_page' );
// 修改自定义文章类型归档页面标题
function change_custom_post_type_archive_title( $title ) {
    if ( is_post_type_archive( 'your-custom-post-type' ) ) {
        $title = 'My Custom post type archive - ' . get_bloginfo('name');
        return $title;
    }
    return $title;
}
add_filter( 'pre_get_document_title', 'change_custom_post_type_archive_title', 9999 );

📄 原文内容

Filters the document title before it is generated.

Description

Passing a non-empty value will short-circuit wp_get_document_title() , returning that value instead.

Parameters

$titlestring
The document title. Default empty string.

Source

$title = apply_filters( 'pre_get_document_title', '' );

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    If you want to change the archive page title of your custom post type then use this code:

    function change_custom_post_type_archive_title( $title ) {
        if ( is_post_type_archive( 'your-custom-post-type' ) ){
            $title = 'My Custom post type archive - ' . get_bloginfo('name');
            return $title;
        }
        return $title;
    }
    
    add_filter( 'pre_get_document_title', 'change_custom_post_type_archive_title', 9999 );