How To Replace A Word In WordPress Posts

In the previous post, you created your very first WordPress plugin. Now let’s make it do something!

How about changing occurrence of a particular word in posts/pages with something else?

For instance, let’s replace pluto with pluto (not a planet). It can be achieved by adding the code below to the plugin file you created in the last post:

function replace_pluto( $text ) {
    return str_replace( 'pluto', 'pluto (not a planet)', $text );
}
  
add_filter('the_content', 'replace_pluto');

That’s all.

What does it do? This code creates a function called replace_pluto and hooks that function into a filter called the_content.

It means whenever the_content is displayed on the front page, it will trigger our function replace_pluto and return the modified text.

Bonus

Similarly, we can also capitalize the first letter of each word by creating a new function and hooking it into the_title filter:

function uc_post_titles( $title ) {
	return ucwords( $title );
}

add_filter( 'the_title', 'uc_post_titles' );

Conclusion

WordPress hooks (i.e. actions and filters) are quite powerful and you’ll use them a lot in WordPress development. You can learn more about them here.