When calling wp_title(), do you have to create some kind of “title.php” file?

… or does wp_title() already handle the various contexts in your blog?

This could clarify for me how I can achieve a reusable index.php file without having all the conditional statements inside it to handle the different title formats in the given context (page, single, posts, search, archive, date, etc…)

Also,

Could a specific post or page have a special custom formatting without breaking the rest of the use-cases? (If this needs to be in a separate question, please let me know – it’s closely tied to this question so I figured I’d merge it in here for now).

2 Answers
2

The wp_title() template tag does some context-based output. From the Codex:

The title text depends on the query:

Single post or a Page

  • the title of the post (or Page)

Date-based archive

  • the date (e.g., “2006”, “2006 – January”)

Category

  • the name of the category

Author page

  • the public name of the user

If you need to add more-specific contextual output, you can use the wp_title filter hook to modify the output.

For example, if you want to prepend the output with the Site Name:

<?php
function mytheme_filter_wp_title( $title ) {
    // Get the Site Name
    $site_name = get_bloginfo( 'name' );
    // Prepend it to the default output
    $filtered_title = $site_name . $title;
    // Return the modified title
    return $filtered_title;
}
// Hook into 'wp_title'
add_filter( 'wp_title', 'mytheme_filter_wp_title' );
?>

Taking an example from the Codex page, say you want to append the site description to the title output when on the site front page:

<?php
function mytheme_filter_wp_title( $title ) {
    // Get the Site Name
    $site_name = get_bloginfo( 'name' );
    // Prepend name
    $filtered_title = $site_name . $title;
    // If site front page, append description
    if ( is_front_page() ) {
        // Get the Site Description
        $site_description = get_bloginfo( 'description' );
        // Append Site Description to title
        $filtered_title .= $site_description;
    }
    // Return the modified title
    return $filtered_title;
}
// Hook into 'wp_title'
add_filter( 'wp_title', 'mytheme_filter_wp_title' );
?>

Modify accordingly, to suit your needs.

In case it isn’t obvious, these filter callbacks belong in functions.php.

EDIT

Missed this:

Could a specific post or page have a special custom formatting without breaking the rest of the use-cases?

It is entirely possible. In fact, that’s how most SEO Plugins work.

Here’s the thing about using the wp_title filter to control wp_title() output: you’ve built in the ability to play nicely with SEO Plugins and anything else that attempts to modify wp_title() content, with no additional code changes required.

Leave a Comment