Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress URL and wp_get_attachment_image_src - http vs https

Tags:

php

wordpress

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?

like image 459
Don Rhummy Avatar asked Nov 30 '22 19:11

Don Rhummy


1 Answers

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);
like image 159
cfx Avatar answered Dec 04 '22 05:12

cfx