Wordpress URL和wp_get_attachment_image_src - http vs https

Don*_*mmy 4 php wordpress

在WordPress的设置,WordPress的URL(它用于大量资源的URL)要求您无论是硬编码http://https://在URL中.这导致在安全站点上加载不安全部件的问题,反之亦然.我该如何处理?

例:

//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 ... ?>
Run Code Online (Sandbox Code Playgroud)

如果用户正在访问https://example.net,则仍将从非安全"http"加载图像.

我如何解决这个问题,以便https中的网站加载https中的所有内容(不仅仅是wp_get_attachment_image_src),反之亦然?

cfx*_*cfx 13

这是WordPress中已知的缺陷/错误,计划在WP 4.0中修复.

与此同时,这是一个WP dev发布的过滤器,我已经取得了巨大的成功:

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);
Run Code Online (Sandbox Code Playgroud)


Mik*_*ike 5

您只需要替换URL字符串中的http即可.

$imageSource = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "myimage" ); 
$output = preg_replace( "^http:", "https:", $imageSource );
echo $output;
Run Code Online (Sandbox Code Playgroud)

您始终可以为所需的功能添加过滤器(例如:add_filter( 'template_directory_uri', function( $original )...始终使用SSL.