Replace a word with a word in the URL string

I’m trying to replace a word on every page for example “Denver” with a word from a URL string, so I’ll have like ?city=Atlanta in the URL. So I was thinking of using PHP’s GET to just get the city from the URL string and str_replace to replace it, but which action/hook in WordPress do I have to attach it to?

The word will appear throughout the entire page, including title, logo description, content, footer, etc… so it can’t just replace content only.

Related posts

2 comments

  1. Check the Filter Reference — there are filters like the_content, the_title, wp_title, etc. I’m not sure what you’d filter to get the logo description and footer — you might need to delve into your theme’s code.

    Also, make sure you sanitize anything you get from $_GETnever ever trust user-generated content. See Data Validation for more information.

  2. str_replace will make a mess of any unlucky markup on the page since it will replace matching text inside of markup or inside of URLs.

    What you want is a modified versions of an answer I gave to another question about highlighting search terms. The change would be to the highlight_search_term function. You just need to alter it to use the $_GET data instead of the search data.

    function highlight_search_term($text){
      if(!empty($_GET['city']){
        $keys = strip_tags($_GET['city']); // nominal validation
        $pattern = '/<[^>].*?>/i';
        preg_match_all($pattern,$text,$matches);
        $placeholders = array();
        foreach ($matches[0] as $v) {
          $placeholders[] = highlight_search_term_placeholders();
        }
        $text = preg_replace_callback($pattern,'highlight_search_term_cb',$text);
        $pattern2 = '/(' . $keys .')/iu';
        $text = preg_replace($pattern2, ' <span class="search-term">1</span> ', $text);
        $text = preg_replace($placeholders,$matches[0],$text);
      }
      return $text;
    }
    

Comments are closed.