2016-11-04 45 views
3

上下文:WordPress 5.4.5,Yoast 3.7.1如何更改WordPress頁面上的標題?

我是一個可以訪問客戶站點的插件開發人員。該網站安裝了Yoast 3.7.1,我想知道這是否意義重大,因爲無論我做什麼,我都無法更改404頁面的title

現在在StackOverflow的其他頁面上提出了類似的問題(例如here,herehere)。那些回答已經詢問header.php是否正確地嵌入了對wp_title()的呼叫。下面是在當前主題的header.php在這一點上:

<title><?php wp_title('|', true, 'right'); ?></title> 

有趣的是,在我的404.php頁,wp_get_document_title()告訴我,該文件標題爲Page not found - XXXX即使上述wp_title調用指定的分隔符,|。 Yoast對標題的重寫已被禁用,所以我一點也不確定這個短跑是從哪裏來的。

我的插件執行REST調用並從外部提取內容以包含在頁面中。該內容的一部分是要在title中使用的文本。

在以前的客戶網站,我已經能夠做到以下幾點:

add_filter('wp_title', 'change_404_title'); 
function change_404_title($title) { 
    if (is_404()) 
    { 
     global $plugin_title; 
     if (!empty($plugin_title)) 
     { 
      $title = $plugin_title; 
     } 
    } 
    return $title; 
} 

然而,在這個網站上,無法運作。

我都試過了,基於WordPress的版本中使用,掛鉤pre_get_document_title過濾器,即

add_filter('pre_get_document_title', 'change_404_title'); 

但同樣無濟於事。我目前正在閱讀Yoast ...

+0

你肯定這個'全球$ plugin_title優先級改變;'變量? –

+0

完全。它被稱爲別的東西,但它絕對存在。 – bugmagnet

回答

6

wp_title自4.4版棄用。所以我們應該使用新的過濾器pre_get_document_title。你的代碼看起來很好,但我很困惑global $plugin_title。我寧願讓你先試試

add_filter('pre_get_document_title', 'change_404_title'); 
function change_404_title($title) { 
    if (is_404()) { 
     return 'My Custom Title'; 
    } 
    return $title; 
} 

如果它不起作用,然後嘗試改變優先級來最近執行你的函數。

add_filter('pre_get_document_title', 'change_404_title', 50); 
+2

我確實喜歡第二個建議的外觀。優先級可能是修復。 – bugmagnet

+1

是的,重點是修復。謝謝。點數和榮譽@KhorshedAlam – bugmagnet

0

添加到您的functions.php

function custom_wp_title($title) { 

    if (is_404()) { 
     $title = 'Custom 404 Title'; 
    } 
    return $title; 
} 
add_filter('wp_title', 'custom_wp_title', 10, 2); 

10 - 是覆蓋其他插件,像SEO

+0

wp_title()最初在4.4中被棄用,但被恢復 – tokas

相關問題