Filter Post Title without affecting screen-reader-text

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

Filter Post Title without affecting screen-reader-text

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x