How to modify the HTML content of a Wordpress post or page with a Plugin

Posted on December 14, 2022

This is the code, that needs to be in a Wordpress Plugin, to modify the HTML content before to send it to the user.

As an example, let's suppose we want to load remote images from the local environment of our Wordpress instance:

function replace_image_base_url($content) {
  
  $content = preg_replace('/src=http:\/\/localhost:8080/u', 'src=https://cdn.yourdomain.com/', $content);
  
  return $content;
}

add_filter('the_content','replace_image_base_url');