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.

mixed-content-loaded-over-https-insecure-script

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/

You might also like

Fix plugins and themes installation when WordPress asks for FTP credentials
When WordPress doesn't have the right premissions on the wp-content folder it will ask for your FTP credentials...

Show executed queries in WordPress with SAVEQUERIES
Once I needed to know which queries were being executed by WordPress. At that moment I configured MySQL...

Install Doctrine2 with PEAR in MacPorts
Run those commands:sudo /opt/local/bin/pear channel-discover pear.doctrine-project.org sudo /opt/local/bin/pear...

Remove a WordPress action in child theme
If you want to remove a WordPress action that was added in the parent theme like this:function...

Leave a Comment