
Are you a WordPress theme developer and you’re running into some frustration with getting the <h1> Title of a page to show properly on archives, categories, search results, and single posts?
I’m an experienced custom WordPress theme developer and this is a little PHP function I put together that handles putting together a page title.
// Dynamic Title
if(!function_exists('wpftw_title')) {
function wpftw_title() {
if (is_home()) {
if (get_option('page_for_posts', true)) {
// Static page home
$title = get_the_title(get_option('page_for_posts', true));
} else {
// Blog posts home
$title = __('Latest posts', 'wpftw');
}
} elseif (is_category()) {
// Category archive
$title = single_cat_title('', false);
} elseif (is_archive()) {
// Other archives
$title = post_type_archive_title();
} elseif (is_search()) {
// Search results
if (trim(get_search_query()) === '') {
$title = __('No search query entered', 'wpftw');
} else {
$title = sprintf(__('Search results for “%s”', 'wpftw'), '<mark>' . trim(get_search_query()) . '</mark>');
}
} elseif (is_404()) {
// 404
$title = __('Page not found', 'wpftw');
} elseif (is_singular()) {
// Single post
$title = single_post_title('', false);
} else {
// Anything else
$title = get_the_title();
}
// Expose my own hook just in case
return apply_filters('wpftw_title', $title);
}
}
To use this in your theme, wherever you have an <h1> title (for example in the theme’s index.php), echo this function like this…
<h1><?php echo wpftw_title(); ?></h1>