Force Post Media to Use SSL

You use encryption, don’t you wish everyone did?

You just bought your SSL certificate, you forced HTTPS from your .htaccess file, but you STILL have the dreaded “mixed content” warning? You could ask your users to use HTTPS for all their media links, but we all know that’s a losing battle. This one simple filter will force all media assets from the Content variable to be requested via HTTPS. You can even set this on a page-by-page basis.

function force_https_content( $content ) {
    
    // Set pages that should be foreced to use HTTPS for their content.
    $securePageArray = array(2, 422, 429, 455, 6, 17, 33, 12, 334, 15, 41, 169, 173, 459, 598);
    
    if ( is_page( $securePageArray ) ) {
        $content = str_replace( 'http://', 'https://', $content );
        return $content;
    }

}
add_filter( 'the_content', 'force_https_content' );

Viola! You now have the happy green lock icon in your address bar. Keep in mind, you may also wish to replace the ‘https://’ above with an empty string. In this way all media links would start with ‘//’ which will allow the browser to request that content with whatever protocol the rest of the page was using. This may be a better solution for a WordPress site that uses a mix of HTTP and HTTPS pages.

12
Mar
2017

Leave a Reply

Your email address will not be published.
*