問題描述

我成功地將我的 4.3.1 安裝轉換為所有的 https 。更新到 4.4 後。我有一個新的 srcset 屬性的問題。雖然使用 https 設置圖像的 src 屬性,但 srcset 屬性為 http 。這導致瀏覽器根本不顯示任何圖像。

在等待更好的修復時,我希望禁用 srcset 屬性的設置,以使所有圖像只有一個 src 屬性。我怎麼做?

最佳解決方案

以下是您可以嘗試刪除 4.4 中響應式圖像支持的幾項:

/**
 * Disable responsive image support (test!)
 */

// Clean the up the image from wp_get_attachment_image()
add_filter( 'wp_get_attachment_image_attributes', function( $attr )
{
    if( isset( $attr['sizes'] ) )
        unset( $attr['sizes'] );

    if( isset( $attr['srcset'] ) )
        unset( $attr['srcset'] );

    return $attr;

 }, PHP_INT_MAX );

// Override the calculated image sizes
add_filter( 'wp_calculate_image_sizes', '__return_false',  PHP_INT_MAX );

// Override the calculated image sources
add_filter( 'wp_calculate_image_srcset', '__return_false', PHP_INT_MAX );

// Remove the reponsive stuff from the content
remove_filter( 'the_content', 'wp_make_content_images_responsive' );

但是如 @cybmeta 所提到的,問題可能在其他地方。

強制 https srcset

您可以使用 wp_calculate_image_srcset 過濾器進行一些調試,甚至嘗試使用此 quick-fix:

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

}, PHP_INT_MAX );

將 URL 方案設置為 https 。另一種方法是使其無模式//

查看其他 set_url_scheme()選項的 Codex:

$source['url'] = set_url_scheme( $source['url'], null );        
$source['url'] = set_url_scheme( $source['url'], 'relative' );

但您應該嘗試深入挖掘並找出根本原因。

更新:

我們可以從 wp_calculate_image_srcset()功能中提前救出:

add_filter( 'wp_calculate_image_srcset_meta', '__return_null' );

然後使用 wp_calculate_image_srcsetmax_srcset_image_width 過濾器。

次佳解決方案

最簡單和最乾淨的做法就是這樣做:

function disable_srcset( $sources ) {
return false;
}
add_filter( 'wp_calculate_image_srcset', 'disable_srcset' );

為了回應大多數其他人所説的話,srcset 是一個好主意和未來,但是如果您需要一個快速修復來保持網站的正常運行,上述代碼段將無需任何黑客攻擊。

來源:WP Core Blog

第三種解決方案

很可能,srcset 屬性中的 URL 錯誤地顯示 HTTPS 的原因是因為所有圖像的 URL 都是使用 wp_options 表中的 siteurl 選項的值構建的。如果您通過 HTTPS 提供前端服務,您還應該更改這些值 (通過 「設置」>「常規」) 。

以下是 WordPress 問題跟蹤系統上的相關票證:https://core.trac.wordpress.org/ticket/34945

第四種方案

這將通過消除比 1 像素更寬的圖像來禁用 srcset 代碼。

add_filter( 'max_srcset_image_width', create_function( '', 'return 1;' ) );

從長遠來看,您應該儘量解決實際的問題。但是,如果您需要快速修復,則可以正常工作。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。