How to change a text dynamically in WordPress using PHP?

A simple PHP filter snippet to replace any hardcoded text output on your WordPress site dynamically, without editing theme files. Drop into functions.php.

Problem: You need to change the text of something in WordPress but cannot figure out where to change it or it’s simply not possible to change it using the theme options.

The following code snippet will help you change any text dynamically using PHP.

  1. Copy the code snippet in functions.php
  2. Replace ORIGINALTEXT by whatever text you want to change on your website.
  3. Replace New Text by whatever you want and save.
  4. Important: the text you replace is case sensitive

This method acts on the HTML rendered by PHP, so it does not reach text re-injected afterwards by an AJAX call, such as WooCommerce shipping labels. For those you have to run again after the call, with the method in running jQuery after an AJAX call. And to output a shortcode inside a template file rather than replace text, see displaying a shortcode in a template.

function start_modify_html() {
  ob_start();
}

function end_modify_html() {
  $html = ob_get_clean();
  $html = str_replace( 'ORIGINALTEXT', 'New Text', $html );
  $html = str_replace( 'originaltext', 'New Text', $html );

  echo $html;
}

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