WordPress: srcset gets HTTP instead of HTTPS in all posts

In WordPress 4.4 images get automatically a srcset attribute. My problem with this was the following (I solved it while I was writing this question, see my answer below):

  • in order to transit everything to https, I replaced all the src="http://... references in the posts table by src="https://... (I changed it later to src="//... for supporting both protocols);
  • the images on all the posts get the correct URL in the src attribute;
  • however in all the images that get the srcset attribute the URLs in it are always with http:// references.

Why does this happen? Why these URLs don’t get my newly updated https:// beginnings?

Related posts

3 comments

  1. If you don’t want to change your WordPress Address (URL) to https then just put this code inside your active themes functions.php file

    function codextent_ssl_srcset( $sources ) {
        foreach ( $sources as &$source ) {
            $source['url'] = set_url_scheme( $source['url'], 'https' );
        }
        return $sources;
    }
    add_filter( 'wp_calculate_image_srcset', 'codextent_ssl_srcset' );
    

    ** Also add this in top line of wp-config.php file.

    $_SERVER['HTTPS'] = 'on';
    
  2. After searching for a while in the wp-includes folder, the wp_calculate_image_srcset method in the media.php file uses these 2 lines:

    $image_baseurl = _wp_upload_dir_baseurl();
    $image_baseurl = trailingslashit( $image_baseurl ) . $dirname;
    

    And this $image_baseurl will actually form the new URL for the srcset attribute, i.e. even if the entire URL is in the wp_poststable and used in the src attribute, its beginning won’t be used.

    This means that if your base url in the wp_options table is still in http://, the images will get that protocol and won’t show up by default by your browser when navigating in https.

    For solving this, you just need to change the URLs inside the option_value in the wp_options table to https:// or just // if you still want to support both protocols (double slashed). You can do this in a single query:

    UPDATE `wp_options`
     SET `option_value` = replace(option_value, 'http://', '//')
     WHERE `option_name` IN ('siteurl', 'home')
    

Comments are closed.