1

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

4

1 回答 1

1

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!

于 2020-01-22T20:48:24.660 回答