Using the template_redirect
hook, you have access to all the HTML that will be rendered to the page. You can use this hook to turn on Output Buffering, find and replace anything you want, and then return the output back, whether it's been modified or not.
Keep in mind this won't cover any iframes that are loaded dynamically with lazy loading, AJAX requests, etc - but anything that's loaded into the HTML at runtime will be in here.
add_action( 'template_redirect', 'global_find_replace', 99 );
function global_find_replace(){
ob_start( function( $buffer ){
/**
*`$buffer` contains your entire markup for this page, at run time.
* anything dynamically loaded with JS/Ajax, etc won't be in here
*/
// Did they accept the GDPR cookie?
if( !isset($_COOKIE['gdpr_consent']) ){
// Nope. Build a simple "accept cookies" notice
$notice = '<div class="accept-cookies">You must accept cookies to see this content</div>';
// Replace all youtube iframes regardless of class, id, other attributes, with our notice
$buffer = preg_replace( '/<iframe.+src="https?:\/\/(?:www.)?youtu\.?be(?:\.com)?.+<\/iframe>/i', $notice, $buffer );
}
// Always return the buffer, wither it was modified or not.
return $buffer;
});
}
Here's the regex I whipped up for the youtube videos, feel free to modify it if I missed anything: https://regex101.com/r/2ZQOvk/2/
This should be more than enough to get you started though!