Fernando Papaqui

fp/dev

How to replace text in WordPress with hooks

Recently a customer asked me to replace the text “Law Office” for “Law Office & McGill” on his WordPress website. The problem was that this website had around 77 pages and 55 blog posts and probably 80% of the content had the text to replace.

The way I solved this problem was by using the WordPress add_filter(); hook and the PHP str_replace(); function which made my life easier, and my customer happy. This approach is also SEO friendly, which is a win-win situation.

The code in functions.php

function replace_text($my_text){
  $my_text = str_replace('Law Office', 'Law Office & McGill', $my_text);
  return $my_text;
}

add_filter('the_content', 'replace_text');

In this case I used ‘the_content’ as the hook but there’s a whole list of options to use.

Fernando Papaqui

Front end web developer working with Gatsby, JS, React, and WordPress. Mexico native.