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' );
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');