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

replace all youtube iframes before cookie consent accepted

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

使用 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,找到并替换你想要的任何东西,然后 return 返回输出,无论它是否被修改。

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;
    });
}

这是我为 youtube 视频制作的正则表达式,如果我遗漏了任何内容,请随时修改它:https://regex101.com/r/2ZQOvk/2/

这应该足以让您入门了!