Use HTTPS protocol in WordPress 4.4+ for srcset attribute
I’ve started using “Let’s Encrypt” in multiple sites I manage. Just after installing it for this blog I noticed that all images didn’t load because they were originally linked with HTTP.
This was easy to fix with a simple SQL update:
UPDATE wp_posts SET post_content = replace(post_content, 'http://tech.enekochan.com', 'https://tech.enekochan.com');
But I still got the “Mixed Content” error messages. Looking at the generated page source code I found that WordPress 4.4+ adds a responsive image attribute to images img
tags: srcset
. And the problem was that the links there were using HTTP. Adding this code in functions.php
solved the issue:
/*
* Force URLs in srcset attributes into HTTPS scheme.
* This is particularly useful when you're running a Flexible SSL frontend like Cloudflare
*/
function ssl_srcset( $sources ) {
foreach ( $sources as &$source ) {
$source['url'] = set_url_scheme( $source['url'], 'https' );
}
return $sources;
}
add_filter( 'wp_calculate_image_srcset', 'ssl_srcset' );
Ref: https://wordpress.org/support/topic/responsive-images-src-url-is-https-srcset-url-is-http-no-images-loaded#post-7767555
https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/