Filter Post Title without affecting screen-reader-text
Question
Let's consider this code:
add_filter('the_title', static function ($title) {
return $title. '-boom';
});
Works fine, and adds '-boom' near all the titles.
But, I also noticed that in some themes (Twenty Twenty, Twenty One and most likely many others) if a post contains the <!--more-->
tag, this also affect the "continue reading" button, see image attached
As you can see the span class "screen reader text" is also affected. Since I want to add some html close to the_title, this breaks the layout.
How to solve?
Solution
Ok, I found a solution.
I've found the filter excerpt_more
that is used to show the string shown within the more link (if theme use standard WP functions).
So, to achieve this, we need to hook the excerpt_more
and use a lower priority of the one used by the theme.
In my example, this
add_filter('the_title', static function ($title) {
return $title. '-boom';
});
adds -boom
string in both text and excpert, and this
add_filter('excerpt_more', function ($more_link_element) {
$more_link_element = str_replace('-boom', '', $more_link_element);
return $more_link_element;
},9999,1);
removes it from the excpert