Reusable hero or banner partials often require more robust title-sniffing operations given to their placement inside or outside of The Loop™. In these, a simple the_title()
call sometimes won't suffice, so you'll have to figure out what kind of view you're looking at and adjust the title accordingly.
If you don't want to do all that yourself, you can let WP do it via its wp_get_document_title()
function. It'll check if the user is viewing archives, doing a search, etc. so you don't have to, and it'll return to you a title in the form of Title - Site Name
. You can then lop off the bits you don't need.
function document_title($echo = true) {
add_filter('document_title_separator', '__return_empty_string');
$title = explode(' ', wp_get_document_title())[0];
remove_filter('document_title_separator', '__return_empty_string');
if ($echo) echo $title;
return $title;
}
By temporarily resetting the document separator to an empty string, the title will now be in the form Title Site Name
. Splitting it on those two spaces will leave you with a two-part array containing the current document title and the site title. Grab that first part and you're good… Maybe.
Aside: I source these posts out of my personal notes, randomly grabbing them when I feel like posting something. Since the web is an ever-evolving place, for better or worse, sometimes things become obsolete or at least a bit outdated. In this case, WP v5.8 added another hook, document_title
, that runs after the one used above. Applying this hook is the last thing wp_get_document_title()
does before returning, so you can tap into that instead if you'd like.
Unfortunately, Yoast and other SEO plugins can get in the way of title-related things. I don't know if it's still the case, but there was definitely a time when Yoast completely bypassed the built-in wp_get_document_title()
function, thus never running the following hooks, in favor of its own processes:
pre_get_document_title
document_title_separator
document_title_parts
document_title
Any attempts to latch onto these would result in nothing happening, and that's always a very fun coding thing to debug. If you find this is the case, you'll have to do some digging to find a solution that works with your SEO plugin. Yoast has a wpseo_title
hook, for instance, but you can also dig out its document separator setting:
$sep = YoastSEO()->helpers->options->get_title_separator();
There's almost always multiple solutions to a given problem, so finding the right one for your current situation is half the battle.