Wordpress 4.4.0+ 自定義頁面title標籤的方法

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');
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章