WordPress version 4.5.1
I’m trying to dynamically update page titles on a particular template. After lots of digging and learning about the wp_title()
changes, I’m attempting to use document_title_parts
. However, I can’t get the filter to run at all.
I’m in a child theme, functions.php
:
add_theme_support( 'title-tag' );
//add_filter("after_setup_theme", function(){ add_theme_support("title-tag"); });
add_filter( 'document_title_parts', function( $title )
{
error_log('here');
return $title;
}, 10, 1 );
I’ve tried both variations of adding theme support as shown above, but watching my log, nothing appears on page reload. That error_log
was working with other functions (such as wp_title
), so the error logging is working.
I’ve also tried pre_get_document_title
, which does fire on page load, though I’m unable to get it to actually change the title.
So! I’m either using the filter wrong, didn’t set up my theme correctly, or something else I’m unaware of. Any help would be greatly appreciated!
edit to add more detail
Attempting an init function, but that also isn’t working: https://gist.github.com/anonymous/6db5af892a4cf4fb029655167d7002a4
Also, while I’ve removed any reference to <title>
from header.php
, the actual site title is still showing up in the source.
I ran your filter in my development area. It didn’t work. Then I switched off the Yoast SEO plugin, which I knew was also messing with the page title. Then it worked. So my suggestion would be another plugin is messing with it.
In the case of Yoast, it was a filter call to pre_get_document_title
returning non empty. In that case wp_get_document_title
is short circuited and the rest of the function, including the documents_title_parts
filter, is not evaluated, as you can see from the first lines of code:
$title = apply_filters( 'pre_get_document_title', '' );
if ( ! empty( $title ) ) {
return $title;
}
So, I took your filter and changed the hook to pre_get_document_title
. It didn’t work. Then I changed the priority to a higher level than the same filter in Yoast. Then it worked. So, I don’t know about your set-up, but I suggest you give this a try:
add_filter( 'pre_get_document_title', function( $title )
{
error_log('here');
return $title;
}, 999, 1 );