If you’re running an eCommerce site on WordPress, you’re running your site over SSL, and thus need to make sure that any other content loaded on the site are also over SSL, otherwise you get nothing. One of the things many stores like to feature is YouTube video content of product demos or similar directly on a product page.

WordPress makes this easy as of version 3.5+ with the introduction of oEmbeds. This allows a content editor in WordPress to simply copy -and-paste a URL from Youtube, or Twitter, or many other services that support the format into the post editor and have it automatically pull in a video or tweet directly into the post.

The Problem

Very slick functionality in itself, but the problem with this is that YouTube doesn’t offer up secure (that is, https://) links to their content that the layperson to copy out of their address bar or grab by copying the share link to embed on a page. This can be frustrating for both the content editor and developers who have to support the site, when complaints of content not showing up properly start coming through. This is of course because insecure assets will not load over a secure connection. Developers know this, but there’s not a ton of reason for others to.

So let’s make them not have to even know about it. As the cosmic entity (a.k.a. “God”) on Futurama once told Bender:

“When you’ve done something right, people won’t be sure you’ve done anything at all.”

The Solution

This code used a string replacement to swap out any instances of http:// with the proper https:// versions and works for both YouTube’s regular URLs and their youtu.be shortener.

/**
 * Replace insecure embeds with secure URLs (https)
 */
add_filter( 'embed_oembed_html', 'embed_secure_content');
add_filter( 'video_embed_html', 'embed_secure_content' ); // Jetpack
function embed_secure_content( $code ) {
    if( strpos( $code, 'youtu.be' ) !== false || strpos( $code, 'youtube.com' ) !== false ) {
        $return = str_replace( 'http://', 'https://', $code );
        return $return;
    }
    return '<div class="embed-container">' . $code . '</div>';
}

It’s highly likely nobody will thank you for this, but give yourself a pat on the back anyway.

NOTE: If you’re also looking for a way to pass YouTube query string parameters on your oEmbed YouTube players automatically, check out my post: Add Query String Parameters to YouTube oEmbeds, which accomplishes it with very similar code to what you see above.

Continue Reading