How to Replace Text in WordPress with functions.php

January 8, 2019

This snippet can be used in a WordPress theme’s functions.php file to dynamically replace text on a specific part of the page. This example replaces text strings in the_content and nowhere else.

function replace_text($text) {
	$text = str_replace('<hr>', '<hr class="hr-small">', $text);
	$text = str_replace('<hr />', '<hr class="hr-small">', $text);
	$text = str_replace('>^<', 'class="rs">^<', $text);
	$text = str_replace('<sup>', '<sup class="rs-sup">', $text);
	return $text;
}
add_filter('the_content', 'replace_text');

Questions?

Find me on Twitter, or send me an email.