Truncate blog post archive titles
There might be cases where you have long blog post archive titles and want to truncate them to a predifined number of words.
You can add a wp_head hook element and write the following PHP snippet which will trancate blog post titles to 7 words:
<?php function wpse_360758_trim_words( $title, $post_id ) { if ( is_admin() ) { return $title; } if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) { $title = wp_trim_words( $title, 7, '...' ); } return $title; } add_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 ); ?>
Activate the Execute PHP checkbox and set the hook element to be displayed on the blog archive only.
How can I ensure that the title does not get truncated on a single post but only truncates on posts archives?
With this solution, single post titles are untouched. Only blog archive titles are affected. Is that not what’s happening on your end?