Changing the wordpress title

wp-logo-smallThe WordPress title is build up from a few elements. One hook (filter) that holds most elements is ‘document_title_parts’. The wp_title() function is great, but it does not let you change the content only the format.

Changing the WordPress title:

The WordPress title is build up out of 4 elements and can be generated with wp_title(). Since 4.4 <title>The title – your blog</title> generating is hooked in wp_head() and more difficult to modify.

Three elements are in the ‘document_title_parts’ filter:

  1. Title – this is usually the title of the post, page, archive
  2. Site – the is the ‘Site Title’ from general settings
  3. Tagline – This is the ‘Tagline’ from general settings
add_filter('document_title_parts', 'change_wp_title', 20, 1);

function change_wp_title($title) {
    global $post, $paged;

    // on single pages prepend the title with Single:
    // AND strip www. from the site title
    if (is_single()) {
        $title['title'] = 'Single: ' . $title['title'];
        $title['site'] = str_replace('www.', ' ', $title['site']);
    }

    // the home page uses a tagline
    if (is_home()) {
        $title['tagline'] = 'Home:';
    }

    if (is_page()) {
        $title['title'] = 'Page: ' . $title['title'];
    }
    if (is_woocommerce()) {
        $title['title'] = 'Shop: ' . $title['title'];
    }

    return $title;
}

The code should be a good example to edit the parts.

Changing the separator:

The fourth element ‘separator’ can be edited with the ‘document_title_seperator’:

add_filter('document_title_separator', 'change_wp_title_sep', 20, 1);

function change_wp_title_sep($sep) {
    // default is: -
    $sep = '*';

    return $sep;
}

One could avoid all, and just change the title:

add_filter('pre_get_document_title', 'wipe_wp_title', 20, 1);

function wipe_wp_title($title) {
    global $post;
    $title = "title for all pages {$post->ID}";

    return $title;
}

 

 

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *