Edit WordPress Page Source On-the-Fly with PHP

On-the-fly ways to use PHP to edit WordPress page source before it leaves the server. Both methods shown here change the page source code before the visitor receives it.

  • None of these PHP methods permanently edit theme template files.
  • None of these methods edit the database.
  • Edits are made to the content output by WordPress as that content is being written by WordPress.
  • All these methods use the PHP function str_replace().
  • str_replace() can be replaced with preg_replace() where regex substitutions are required.
  • These methods affect the source code but not separately loaded resource files
  • With these methods we can edit the HTML, page text, inline CSS and inline scripts.
  • These methods can be used with conditional tests to limit their scope e.g. is_single() or is_category().
  • The code snippets go into a child theme’s functions.php file or a functionality plugin.

Why use PHP to edit WordPress page source?

It is bad practice to edit WordPress core files or WordPress plugin files. File edits are overwritten when WordPress is upgraded or when plugins with edited files are updated. So, what do we do when we need to overwrite core, plugin or theme output?

  • Use filter functions
  • Use .po language files
  • Use JavaScript / jQuery
  • Use CSS (limited effect)
  • Use PHP output buffering

JavaScript, jQuery and CSS all work after page content has already been received by a web browser. This means the original data can be seen in the page source.

Language files are useful when we want to edit text strings that have been written in a manner that allows data in .po files can be applied to those strings. We can use tools like Poedit to help manage these files.

This post concentrates on PHP methods to intercept WordPress page content as it is built by PHP. When we intercept PHP we can edit the state of whatever has been processed up to the point of interception. For example,

  • We can add target=”_blank” to all links then append an ‘opens in new tab’ icon to every closing link tag.
  • We can replace words in a page with other preferred words.
  • We can replace image URLs with new image URLs.
  • We can replace one URL for another URL before a page leaves the web server.

All this can be done on-the-fly with PHP as pages are being prepared on the server ready to be sent to a visitor. The visitor will never know the page has been edited on the server.

The two ways to edit PHP page output described here intercept WordPress at different points of operation:

  • Method 1 targets specific WordPress filters such as the_content() and the_title().
  • Method 2 intercepts WordPress after WordPress, all plugins, and the theme are fully loaded and instantiated.

Method 2 is the catch-all option. All output is acted on by method 2. Method 1 is restricted to act on only a specified area of the output; this area is set by the WordPress filter called by add_filter().

Method 1:Replace or modify output by use of a specific WordPress filter

The following PHP snippet edits text in the post content of a page but not the header, not the footer or and not the sidebars.

<?php

/**
* Replace Text in post content
**/

function vr_replace_content($content) {

      $find = array('One', 'Two', 'Three'); // The items to replace
      $replace  = array('Uno', 'Dos', 'Tres'); // Their replacements

      $content = str_replace($find, $replace, $content); // $finds strings in the $content to $replace
      return $content; // The filtered content

}
add_filter('the_content','vr_replace_content'); // This injects vr_replace_content() into the filter the_content(). The normal output of the_content() is altered by the custom function vr_replace_content()

The line add_filter(‘the_content’, ‘vr_replace_content’) tells WordPress to apply the find and replace function vr_replace_content() to the WordPress content filter the_content().

Instead of the_content() we could use the_title(), the_content_feed(), the_excerpt(), author_link() or any number of built in filters or even a plugin’s or theme’s own filters. We can use this snippet to affect any usable filter.

Conditional application

This next example snippet is useful when WPML (WordPress Multilingual) is installed in a site. This example snippet filters the_content() differently for each language version of a site. In this case those language versions are English (en) and Spanish (es). The conditional test applied against the WPML variable ICL_LANGUAGE_CODE.

Notice that to prevent site breakage we confirm the function icl_object_id() exists before we test against ICL_LANGUAGE_CODE. If icl_object_id() does not exist then the search and replace code is not run.

<?php

/**
* Replace Text in the_content() of Spanish & English sites
**/

function vr_replace_strings($content) {
    if ( function_exists('icl_object_id') ) {
        if(ICL_LANGUAGE_CODE==es){
            $find = array('Inglés');
            $replace  = array('English');
        }
        if(ICL_LANGUAGE_CODE==en){
            $find = array('Spanish');
            $replace  = array('Español');
        }
        $content = str_replace($find, $replace, $content);
    }
    return $content;
}
add_filter('the_content','vr_replace_strings', 100);

We can use other tests to ensure our find and replace function only works when specific categories or pages are in view with is_category() or is_page().

Method 2: Replace or modify output anywhere in a page

This method uses PHP output buffering. We capture the whole of the output from WordPress and hold the output in the PHP output buffer. We edit the output that is held in the buffer then release the edited output to the visitor.

Notice we first test we are not in the admin area of the site. We typically only need to edit the output of the frontend of a WordPress site not the admin dashboard area of the site.

<?php

/**
* Replace anything anywhere in the page output
**/

if ( !is_admin() ) {

    function vr51_callback($buffer) {

        $find = array('One', 'Two', 'Three');
        $replace  = array('Uno', 'Dos', 'Tres');

        $buffer = str_replace($find, $replace, $buffer);
        return $buffer;
        
    }

    add_action('wp_loaded', 'buffer_start');    function buffer_start() { ob_start("vr51_callback"); }
    add_action('shutdown', 'buffer_end');       function buffer_end()   { ob_end_flush(); }
    
}

This function can be used to edit HTML, text and inline scripts and inline CSS shown in the page source anywhere within the whole of the page source. Externally loaded resource files are not affected by this function.

Over to you

How do you like to edit WordPress page output before it leaves the server? What tips can you share?

Sharing is caring!

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x