Title tags in WordPress
Published June 13th, 2012 under General
Including convoluted chunks of code to WordPress themes so that you can provide support for advanced title tags is mostly pointless since the same functionality is provided by SEO plugins for those who require it. However, if you are releasing themes to the public, then you don’t want to leave them blank. You also don’t want to be adding junk to your header.php file as this will only mess up the SEO plugins’ ability to edit it. The solution here is to use a WordPress filter to do some basic filtering of the wp_title() function which you add to your theme as follows:
Example header.php file
<!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <title><?php wp_title(); ?></title> <?php wp_head(); ?> </head> <body <?php body_class(); ?>>
You can then use the following snippet of code to do some very basic filtering, adding basic support for title tags.
Example functions.php
<?php /* * Print the title tag based on what is being viewed. * * @author Ryan Hellyer <ryanhellyer@gmail.com> * @return string */ function themeprefix_title() { $title = ''; // Single post if ( is_single() ) { $title .= single_post_title( '', false ); $title .= ' | '; $title .= get_bloginfo( 'name' ); } // Home page elseif ( is_home() ) { $title .= get_bloginfo( 'name' ); $title .= ' | '; $title .= get_bloginfo( 'description' ); if ( get_query_var( 'paged' ) ) $title .= ' | ' . __( 'Page', 'themename' ) . ' ' . get_query_var( 'paged' ); } // Static page elseif ( is_page() ) { $title .= single_post_title( '', false ); $title .= ' | '; $title .= get_bloginfo( 'name' ); } // Search page elseif ( is_search() ) { $title .= get_bloginfo( 'name' ); $title .= ' | Search results for ' . esc_html( $s ); if ( get_query_var( 'paged' ) ) $title .= ' | ' . __( 'Page', 'themename' ) . ' ' . get_query_var( 'paged' ); } // 404 not found error elseif ( is_404() ) { $title .= get_bloginfo( 'name' ); $title .= ' | ' . __( 'Not Found', 'themename' ); } // Anything else else { $title .= get_bloginfo( 'name' ); if ( get_query_var( 'paged' ) ) $title .= ' | ' . __( 'Page', 'themename' ) . ' ' . get_query_var( 'paged' ); } return $title; } add_filter( 'wp_title', 'themeprefix_title' ), 1 );
This isn’t the ultimate solution to title tags. For optimum results, you should use an SEO plugin such as WordPress SEO by Joost de Valk.
Ryan says:
I made a small edit to this as it was failing on archive pages.
July 22, 2012 at 4:48 am # //