在接受 cookie 同意之前替换所有 youtube iframe

这是针对 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。


aluckdog
浏览 84回答 1
1回答

慕虎7371278

使用该template_redirect钩子,您可以访问将呈现到页面的所有 HTML。您可以使用此挂钩打开输出缓冲,查找和替换您想要的任何内容,然后返回输出,无论它是否已被修改。请记住,这不会涵盖通过延迟加载、AJAX 请求等动态加载的任何 iframe - 但在运行时加载到 HTML 中的任何内容都将在此处。add_action( 'template_redirect', 'global_find_replace', 99 );function global_find_replace(){&nbsp; &nbsp; ob_start( function( $buffer ){&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*`$buffer` contains your entire markup for this page, at run time.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* anything dynamically loaded with JS/Ajax, etc won't be in here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; // Did they accept the GDPR cookie?&nbsp; &nbsp; &nbsp; &nbsp; if( !isset($_COOKIE['gdpr_consent']) ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Nope. Build a simple "accept cookies" notice&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $notice = '<div class="accept-cookies">You must accept cookies to see this content</div>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Replace all youtube iframes regardless of class, id, other attributes, with our notice&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $buffer = preg_replace( '/<iframe.+src="https?:\/\/(?:www.)?youtu\.?be(?:\.com)?.+<\/iframe>/i', $notice, $buffer );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Always return the buffer, wither it was modified or not.&nbsp; &nbsp; &nbsp; &nbsp; return $buffer;&nbsp; &nbsp; });}这是我为 youtube 视频制作的正则表达式,如果我错过任何内容,请随时修改它:https ://regex101.com/r/2ZQOvk/2/这应该足以让你开始!
打开App,查看更多内容
随时随地看视频慕课网APP