Using WordPress ‘pre_get_document_title’ PHP filter

pre_get_document_title is a WordPress PHP filter that allows you to modify the document title before it’s generated.

Usage

add_filter('pre_get_document_title', 'your_custom_function');
function your_custom_function($title) {
    // your custom code here
    return $title;
}

Parameters

  • $title (string) – The document title. Default empty string.

More information

See WordPress Developer Resources: pre_get_document_title

Examples

Add a custom prefix to the document title

This example adds a custom prefix “My Site – ” to the document title.

add_filter('pre_get_document_title', 'add_custom_title_prefix');
function add_custom_title_prefix($title) {
    $title = "My Site - " . $title;
    return $title;
}

Set a custom document title for a specific page

This example sets a custom document title for a specific page with ID 42.

add_filter('pre_get_document_title', 'set_specific_page_title');
function set_specific_page_title($title) {
    if (is_page(42)) {
        $title = 'Custom Title for Page 42';
    }
    return $title;
}

Append a custom suffix to the document title

This example adds a custom suffix ” – Powered by Awesome” to the document title.

add_filter('pre_get_document_title', 'add_custom_title_suffix');
function add_custom_title_suffix($title) {
    $title .= " - Powered by Awesome";
    return $title;
}

Set a custom title for 404 error pages

This example sets a custom document title for 404 error pages.

add_filter('pre_get_document_title', 'set_custom_title_for_404');
function set_custom_title_for_404($title) {
    if (is_404()) {
        $title = "Oops! Page Not Found";
    }
    return $title;
}

Replace the document title with the site tagline

This example replaces the document title with the site tagline.

add_filter('pre_get_document_title', 'replace_title_with_tagline');
function replace_title_with_tagline($title) {
    $title = get_bloginfo('description');
    return $title;
}