4.4.0版本前,使用wp_title()
是很普遍的。而4.1.0
引入了title-tag,可以使用
function theme_slug_setup() {
add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'theme_slug_setup' );
來加入theme
支持。
4.4.0
版本開始,加入了wp_get_document_title()這個函數,而wp_title
已經deprecated
不推薦使用。
在header.php
中,
<title><?php echo wp_get_document_title(); ?></title>
在functions.php
裏,添加如下代碼:
<?php
function custom_document_title_separator()
{
$separator = ' | ';
return $separator;
}
add_filter('document_title_separator', 'custom_document_title_separator');
function reform_page_title($title)
{
$title['tagline'] = 'Site description when on home page.';
$title['page'] = 'Page number if paginated.';
$title['site'] = 'Site title when not on home page.';
return $title;
}
add_filter('document_title_parts', 'reform_page_title', 10, 1);
?>
以上代碼中custom_document_title_separator
用於添加自定義的分隔符號,reform_page_title
是調用document_title_parts
這個hook
的時候,我們可以對已經生成的title
進行二次修改。所以如果不使用這個hook
,也是完全沒有問題的。
這樣一來,頁面的title
就都已經生成好了!
注意:
如果使用了Yoast SEO
這個插件,那麼我們需要在激活插件後在functions.php
中添加以下代碼(WPSEO (~3+) and WordPress (4.4+))來阻止title
被重寫:
function disableYoastTitleRewrite() {
if (class_exists('WPSEO_Frontend') {
$wpseo_front = WPSEO_Frontend::get_instance();
remove_filter( 'pre_get_document_title', array( $wpseo_front, 'title' ), 15 );
remove_filter( 'wp_title', array( $wpseo_front, 'title' ), 15 );
}
}
add_action( 'init', 'disableYoastTitleRewrite');