【问题标题】:replace all youtube iframes before cookie consent accepted在接受 cookie 同意之前替换所有 youtube iframe
【发布时间】:2020-01-22 20:08:09
【问题描述】:
这是针对 GDPR cookie 政策的。
因为 youtube 使用 cookie,我必须阻止 youtube 视频,并且只有在接受 cookie 政策时才授予访问权限。
所以我需要类似的东西:
if(!isset($_COOKIE['consentaccept'])) {
// replace all iframes from https://www.youtube.com/ with:
//<div class="youtubeblock">you must enable cookies to view this video</div>
}
或者你有更好的解决方案
有什么想法吗?
这是 WordPress。
【问题讨论】:
标签:
php
wordpress
gdprconsentform
【解决方案1】:
使用template_redirect 挂钩,您可以访问将呈现到页面的所有HTML。你可以使用这个钩子打开Output Buffering,找到并替换你想要的任何东西,然后返回输出,不管它是否被修改过。
请记住,这不会涵盖任何通过延迟加载、AJAX 请求等动态加载的 iframe - 但在运行时加载到 HTML 中的任何内容都将在此处。
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;
});
}
这是我为 youtube 视频制作的正则表达式,如果我遗漏了任何内容,请随时修改:https://regex101.com/r/2ZQOvk/2/
这应该足以让你开始!