I found two solutions to replace text in WordPress page. Both are working "almost" fine, except for a few issues:
Solution 1:
function callback($buffer) {
// modify buffer here, and then return the updated code
return $buffer;
}
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }
add_action('wp_head', 'buffer_start');
add_action('wp_footer', 'buffer_end');
It is taken from:
WordPress filter to modify final html output and
http://www.dagondesign.com/articles/wordpress-hook-for-entire-page-using-output-buffering/
It works fine but it does not allow change of page title. Is there any way to change page title in above method?
The second solution I got from a popular plugin (code line no. 270): https://wordpress.org/plugins/real-time-find-and-replace/
function far_template_redirect() {
ob_start();
ob_start( 'far_ob_call' );
//ob_end_flush(); fails here. I don't know why?
}
//Handles find and replace for public pages
add_action( 'template_redirect', 'far_template_redirect' );
It works fine, but many links online suggest that add_filter 'template_include'
should be used instead of add_action 'template_redirect'
. See:
https://markjaquith.wordpress.com/2014/02/19/template_redirect-is-not-for-loading-templates/ https://bbpress.trac.wordpress.org/ticket/1524
But if I try add_action 'template_redirect'
instead of add_filter 'template_include'
, the text replace code works on some websites and breaks some other websites.
And people suggested that ob_end_flush()
must be used with ob_start()
, but the code fails if I include ob_end_flush
in code after ob_start
.
I like the solution 1
, but is there any way to include headers and footers in it? Otherwise Solution 2
works for all websites, except that it does not have ob_end_flush
and not recommended by many people, though a popular plugin uses it.