Skip to content

Instantly share code, notes, and snippets.

@rmpel
Created August 9, 2024 06:11
Show Gist options
  • Save rmpel/56a4c8e43d7cd57058c683c12f139c55 to your computer and use it in GitHub Desktop.
Save rmpel/56a4c8e43d7cd57058c683c12f139c55 to your computer and use it in GitHub Desktop.
Privacy friendly video embeds in WordPress
<?php
// This will make WordPress ALWAYS use privacy friendly embeds, implemented here are YouTube and Vimeo.
// Other services can be implemented by using this code as inspiration.
add_filter( 'oembed_dataparse', 'myproject_patch_oembed_urls', 11 );
function myproject_patch_oembed_urls( $html ) {
// find vimeo.com urls and add ?dnt=1 to them.
$urls = wp_extract_urls( $html );
foreach ( $urls as $old_url ) {
if ( false !== strpos( $old_url, 'vimeo.com' ) ) {
$new_url = add_query_arg( 'dnt', 1, $old_url );
$html = str_replace( $old_url, $new_url, $html );
}
// Embeds of youtu.be (and others) are already translated to youtube.com by WordPress, they all work.
if ( false !== strpos( $old_url, 'youtube.com' ) ) {
$old_url_domain = parse_url( $old_url, PHP_URL_HOST );
// www.youtube-nocookie.com MUST HAVE www. in the domain because the non-www version does not have a valid SSL certificate. #GoGoogle #Facepalm.
$new_url_domain = 'www.youtube-nocookie.com';
$new_url = str_replace( "//$old_url_domain", "//$new_url_domain", $old_url );
$html = str_replace( $old_url, $new_url, $html );
}
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment