the_title
Filters a post's title wherever get_the_title() is used, including menus and admin lists, so check the context first.
When it fires
WordPress applies the_title inside get_the_title(), which the_title() and many other functions use. So it runs for page headings, post lists, navigation menu items, admin screens, widgets and the REST API.
It doesn't change the title in the browser tab. That comes from wp_get_document_title(); see document_title_parts.
Parameters
$post_titlestring |
The post title. |
|---|---|
$post_idint |
The post ID. |
What to return
The title as a string.
Example: Shorten long titles on archive pages
add_filter( 'the_title', function ( $title, $post_id = 0 ) {
if ( is_admin() || is_singular() || ! in_the_loop() || 'post' !== get_post_type( $post_id ) ) {
return $title;
}
return wp_trim_words( $title, 8 );
}, 10, 2 );
Good to know
- Give $post_id a default value, as in the example. Some plugins apply this filter with the title only, and a required second parameter would then cause a fatal error.
- Avoid adding HTML. Titles are also used in attributes and plain-text places, where markup shows up as text.