Wordpress

How to Customize Post, Archive and Other Page Titles in WordPress

31 OCT 2022

Previously, customizing the page title ( the title appearing between <title> and </title> tags in header ) was a hack job consisting of using the global post variable and then conditional statements!

Conditional statements are still used as needed, but we can now create the page title in a better way!

The first thing to do is, use the add_theme_support function –

add_theme_support('title-tag');

We are adding support for the title tag with the line above. Put this in functions.php file (Typically written inside the after_setup_theme hook callback function.

Then use the wp_head() in header –

<header>
.
.
.
wp_head();
.
.
.
</header>

Now WordPress will generate the page titles automatically!

Assuming that site title is My Site Title and tagline is My Tag Line ( as set from the dashboard), the following rules are used by WordPress while generating titles –

Home page titles are created with a combination of the site title and the tagline with a separator in between. Example: My Site Title – My Tag Line.

Archive page titles are created with a combination of the archive date/month/year and the tagline.
Example: October 8, 2022 – My Tag Line.

Category page titles are created with a combination of the category name and the site title.
Example: General – My Site Title

Author posts page titles are created with a combination of the author name and the site title.
Example: Admin – My Site Title

Page titles are created with a combination of the page title and the site title.
Example: Sample Page – My Site Title.

Post titles are created with a combination of the post title and the site title.
Example: Welcome to my blog – My Site Title

Now, if we want to customize the titles, then we can use the filter document_title_parts

add_filter( 'document_title_parts', 'wp123_filter_wp_title', 10, 2 );
function wp123_filter_wp_title($title_parts)
{    
    // your conditional logic here
    //
    return $title_parts;
}

The callback function wp123_filter_wp_title for this filter takes a parameter $title_parts. This parameter contains the various parts of the title based on the page displayed.

Write your conditional logic there to get the desired result and return the $title_parts.

Note that this method replaces the wp_title filter used in versions of WordPress lower than 4.4.0

Every business deserves a website
हर एक बिजनेस के लिए एक वेबसाइट होना जरूरी है

GET YOUR'S NOW

Address

411 Kalikapur

Ishani Apartments, Kolkata - 99

Contacts

support@webdesignvista.com
Phone: +91 9903490874
Fax: +91 9903490874