Replacing strings in WordPress (without a plugin)

By February 14, 2019 April 2nd, 2019 Customization, Resources

If your theme or one of your plugins outputs text that you would like to replace, but you don’t want to install yet another plugin, here’s a solution for you:

function start_modify_html() {
   ob_start();
}

function end_modify_html() {
   $html = ob_get_clean();
   $html = str_replace( 'old string 1', 'new string 1', $html );
   $html = str_replace( 'old string 2', 'new string 2', $html );
   $html = str_replace( 'old string 3', 'new string 3', $html );
   echo $html;
}

add_action( 'wp_head', 'start_modify_html' );
add_action( 'wp_footer', 'end_modify_html' );

Place that code in your [child] theme’s functions.php and replace the string text as needed.

So what’s happening here?

The start_modify_html() function is called when WordPress hits the <head> section of our site during rendering. The PHP function ob_start() places the output of the PHP script into an internal buffer, as opposed to rendering it out to be delivered to the client.

The rest of the page is generated into this buffer, until – in the footer of the page – the end_modify_html() function is called. This triggers ob_get_clean(), which dumps the contents of the buffer into the $html variable, deletes the output buffer, and turns off output buffering.

We now have the PHP-rendered content of the page load in the $html variable, meaning we can run the str_replace() function to replace specific strings in it. Once we’ve replaced all the strings we want, we echo the $html content. This returns the HTML to continue the page load, and the visitor sees the content.

All of this happens on the server, before the content is returned to the visitor, meaning it is completely transparent. Should you only be running a couple of str_replace() calls, the impact to performance should be negligible.

Source: StackExchange