Armfoot
Armfoot

Reputation: 4921

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):

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

Upvotes: 5

Views: 6273

Answers (3)

Codextent
Codextent

Reputation: 444

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';

Upvotes: 5

Kulbhushan Sehrawat
Kulbhushan Sehrawat

Reputation: 51

Change Following Setting in admin under Setting->General:

WordPress Address (URL) : https://yoursitename.com Site Address (URL) : https://yoursitename.com

And press [Save Changes] button. Finally refresh your page and your image will be displayed on your browser with correct srcset attribute.

Upvotes: 5

Armfoot
Armfoot

Reputation: 4921

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')

Upvotes: 4

Related Questions