Context: WordPress 5.4.5, Yoast 3.7.1
I'm a plugin developer who has access to the client's site. The site has Yoast 3.7.1 installed and I'm wondering if that is significant because no matter what I do I can't change the 404 page's title
.
Now on other pages on StackOverflow where similar questions have been posed (here, here and here for example), those answering have asked if the header.php
is correctly embedding a call to wp_title()
. Here's what's in the current theme's header.php
at that point:
<title><?php wp_title( '|', true, 'right' ); ?></title>
Interestingly, in my 404.php
page, wp_get_document_title()
tells me that the document title is Page not found - XXXX
even though the wp_title
call above specifies the separator as |
. Yoast's rewriting of titles has been disabled so I'm not at all sure where that dash is coming from.
My plugin does a REST call and pulls in content from off-site for inclusion in the page. Part of that content is the text to be used in the title
.
On previous client sites, I've been able to do the following:
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;
}
However, on this site, that's not working.
I have tried, based on the version of WordPress being used, hooking the pre_get_document_title
filter, viz
add_filter('pre_get_document_title', 'change_404_title');
but again to no avail. I am currently reading up on Yoast ...
wp_title
deprecated since version 4.4. So we should use the new filter pre_get_document_title
. Your code looks fine but I am confused about global $plugin_title
. I would rather ask you to Try this first
add_filter('pre_get_document_title', 'change_404_title');
function change_404_title($title) {
if (is_404()) {
return 'My Custom Title';
}
return $title;
}
If it doesn't work then try changing the priority to execute your function lately.
add_filter('pre_get_document_title', 'change_404_title', 50);