WordPress: Get Raw Document Title without Blog Name

document_title_parts, wp_get_document_title

Sometimes it is necessary to retrieve the current Document Title (used in the title tag) without the blog name or separators. As of WordPress 4.4 the wp_get_document_title() function become available which should be used to fetch the title – unfortunately it doesn’t accept any arguments and it is not possible to access the pure page title directly. Instead we can hook into the document_title_parts filter which allows us to access all title parts (title, page, tagline, site).

Workaround#

// workaround to retrieve the document title
function getDocumentTitle(){
    // temporary title
    $documentTitle = 'Unknown';

    // extractor function
    $extractor = function($parts) use (&$documentTitle){
        if (isset($parts['title'])){
            $documentTitle = $parts['title'];
        }
        return $parts;
    };

    // add filter to retrieve the page title
    add_filter('document_title_parts', $extractor);

    // trigger title generation
    wp_get_document_title();

    // remove filter
    remove_filter('document_title_parts', $extractor);

    // return result
    return $documentTitle;
}