Reputation: 25860
In Wordpress settings, the Wordpress URL (which is used for a lot of resource URLs) requires you to hardcode either http://
or https://
in the URL. This results in issues with insecure parts being loaded on a secure site or vice versa. How do i handle this?
Example:
//The wordpress URL setting (In Settings->General)
http://example.net
//An image source (this is now http://example.net/images/myimage.png)
$imageSource = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "myimage" );
?><img src="<?php echo $imageSource; ?>" .?<?php ... ?>
If the user is visiting https://example.net
, the image will still be loaded from the non-secure "http".
How do I fix this so a site in https loads everything (not just wp_get_attachment_image_src
) in https and vice-versa?
Upvotes: 4
Views: 8598
Reputation: 3441
This is a known defect/bug in WordPress and is scheduled to be fixed in WP 4.0.
In the meantime, here is a filter a WP dev posted that I've had great success with:
function ssl_post_thumbnail_urls($url, $post_id) {
//Skip file attachments
if(!wp_attachment_is_image($post_id)) {
return $url;
}
//Correct protocol for https connections
list($protocol, $uri) = explode('://', $url, 2);
if(is_ssl()) {
if('http' == $protocol) {
$protocol = 'https';
}
} else {
if('https' == $protocol) {
$protocol = 'http';
}
}
return $protocol.'://'.$uri;
}
add_filter('wp_get_attachment_url', 'ssl_post_thumbnail_urls', 10, 2);
Upvotes: 13
Reputation: 2101
Just to elaborate on @Epik answer - We should be serving an HTTP when HTTP and HTTPS when HTTPS.
We can add some logic that will check using the built in Wordpress function is_ssl() and then either do the preg replace or use the standard http.
$imageSource = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "myimage" );
$output = is_ssl() ? preg_replace( "^http:", "https:", $imageSource ) : $imageSource ;
echo $output;
Upvotes: 0
Reputation: 1446
You would have to just replace the http in the URL string.
$imageSource = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "myimage" );
$output = preg_replace( "^http:", "https:", $imageSource );
echo $output;
You could always add a filter to your required functions (for example: add_filter( 'template_directory_uri', function( $original )
... to always use SSL.
Upvotes: 6