Siyah Siyah - 2 months ago 12
PHP Question

How to trim specific words when getting content from Wordpress?

I have this in my Wordpress template:

$my_content = get_the_content();
$trimmed_content = wp_trim_words( $my_content, 12, '...' );
echo $trimmed_content;

This trims the content I am fetching, but I want to get rid of some words I don't want to show explicitly. So let's say I don't want to show the word "coming" or "world" or "weather" in the content.

How can I achieve that?

And I have one rather odd request regarding this. I have some words which I use as tags. So let's say something like this: (tag: hereComesArandomWord)

What I want to do, is to get rid of (tag: ) (so also the last parenthese). Is this possible as well?

Answer Source

str_replace() will operate a search and replace on a string.

The previous answer was more or less on the money. You'd simply execute str_replace() before using wp_trim_words().


$my_content = get_the_content();
$filtered_content = str_replace( array( 'coming', 'world', 'weather' ), '', $my_content );
$trimmed_content = wp_trim_words( $filtered_content, 12, '...' );
echo $trimmed_content;