Context: WordPress 5.4.5 and Yoast SEO 3.7.1
I’m a plugin developer who has access to the client’s site. The site has Yoast 3.7.1 installed. Is that significant, because no matter what I do I can’t change the 404 page’s title
?
Now on other pages on Stack Overflow, 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, on 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…
3
Answers
wp_title
has been deprecated since version 4.4. So we should use the new filterpre_get_document_title
. Your code looks fine, but I am confused aboutglobal $plugin_title
. I would rather ask you to try this first:If it doesn’t work then try changing the priority to execute your function late.
Add this to your functions.php
10 – is priority change to overwrite other plugins like SEO
How the document title is generated has changed since WordPress v4.4.0. Now
wp_get_document_title
dictates how the title is generated:Here is the code from v5.4.2. These are the filters you can use to manipulate the title tag:
So here are two ways you can do it.
The first one uses the
pre_get_document_title
filter which short circuits the title generation and is hence more performant if you are not going make changes on the current title:The second way uses the
document_title_separator
anddocument_title_parts
hooks for the title and the title separator that are executed later in the function, after the title is generated using functions likesingle_term_title
orpost_type_archive_title
depending on the page, and just before the title tags is about to be outputted: