DIY SEO Titles in WordPress

By default, WordPress displays the name of your blog first in the HTML “title” element. That’s not good for search engines or TrackBacks because it obfuscates the title of your post or page, which is what people (and Google) are really interested. There are at least two existing plugins that address this—SEO Title Tag and Optimal Title—but it’s really not that hard to do yourself, provided you’re not afraid of a little PHP.

The first thing you need to do is create a file in your theme directory called functions.php. If you’ve already got one of these, then obviously you don’t need this step.

Next, paste this function into your file:

function my_title() {
    $blog = get_bloginfo('name');
    $sep = ' | ';
    $result = '';

    if ( is_404() ) {
        $result = 'Oops!' . $sep . $blog;
    } else {
        if( wp_title('', false) ) {
            $result = wp_title('', false) . $sep;
        }
        $result .= $blog;
    }

    return $result;
}

This code is basically an example from the Codex with some slight modifications. Primarily, I use a variable $sep to set the separator between the post title and the name of the blog. I like the ‘pipe’, but others prefer ‘«’ (aka «). I’ve also set it up to put a page title on the 404 Page Not Found error page. This example could be further customized using other conditional template tags.

Finally, open up the header.php file in your theme directory. Find the HTML title element and change it to

<title><?php echo my_title(); ?></title>

That’s it! Moreover, now we have a framework for further customizing page and post titles. I’ll build on this in a future post.

For more on search-engine optimization, see my del.icio.us bookmarks.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>