I'm searching for a proper way to use OB to modify a script in my head as well as native WP-embeds for Twitter/Reddit in posts on the fly for guest users.
So far, I'm using this (it works for the head script but not for the embeds, unfortunately):
if ( !is_admin() ) {
function change_code($buffer) {
$find = array(
'text/javascript" src="https://www.googletagmanager.com/gtag/js?id=XXX"',
'src="https://platform.twitter.com/widgets.js" charset="utf-8" type="text/javascript"',
'src="https://embed.redditmedia.com/widgets/platform.js" charset="UTF-8" type="text/javascript"');
$replace = array(
'text/plain" src="https://www.googletagmanager.com/gtag/js?id=XXX"',
'src="https://platform.twitter.com/widgets.js" charset="utf-8" type="text/plain"',
'src="https://embed.redditmedia.com/widgets/platform.js" charset="UTF-8" type="text/plain"');
$buffer = str_replace($find, $replace, $buffer);
return $buffer;
}
add_action('wp_loaded', 'buffer_start'); function buffer_start() { ob_start("change_code"); }
add_action('shutdown', 'buffer_end'); function buffer_end() { ob_end_flush(); }
}
A workaround for the embeds would be to address the iFrame-code they're creating. Tried that too, but didn't have any success on this either. In addition, when enabling WP-debug, I get the following error pretty often:
PHP Notice: ob_end_flush(): Failed to delete and flush buffer. No buffer to delete or flush in [...]child/functions.php
(using WP 6.0.3, PHP 8.1.13)
Could somebody help me in finding a way to fix this? Not sure if the code I'm using is still following modern/efficient standards - I found this topic as an alternative, but didn't manage to adjust their solutions to any working degree for my use case (made the modification to the GTag-script stop working also).
Thanks for your time, eC