問題描述

我正在一個基於流體寬度 CSS 模板的工作站點,它將圖像上的 max-width 設置為包含它們的列的寬度,我需要刪除 WordPress 添加到圖像的內聯寬度和高度尺寸屬性。

我用這個過濾器的特色圖片來做:

add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10, 3 );

function remove_thumbnail_dimensions( $html, $post_id, $post_image_id ) {
    $html = preg_replace( '/(width|height)="d*"s/', "", $html );
    return $html;
}

如果需要,我知道我可以將同樣的過濾器應用於 the_content 。但是有沒有更好的方法呢?

最佳解決方案

感謝所有!

image_send_to_editor 過濾器是我正在尋找的… 謝謝 @ t31os 指出它。

這是我現在的職能。

add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 );
add_filter( 'image_send_to_editor', 'remove_thumbnail_dimensions', 10 );

function remove_thumbnail_dimensions( $html ) {
    $html = preg_replace( '/(width|height)="d*"s/', "", $html );
    return $html;
}

這將從使用 the_post_thumbnail()檢索的圖像中刪除內聯維屬性,並防止將這些屬性添加到添加到編輯器的新圖像。不能從通過 wp_get_attachment_image 或其他相關功能 (沒有掛鈎) 檢索的圖像中刪除它們,但必要時可以在模板文件中處理這些情況。

次佳解決方案

修改了這個腳本了一下。謝謝您的幫助!

add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 );
add_filter( 'image_send_to_editor', 'remove_thumbnail_dimensions', 10 );
// Genesis framework only
add_filter( 'genesis_get_image', 'remove_thumbnail_dimensions', 10 );
// Removes attached image sizes as well
add_filter( 'the_content', 'remove_thumbnail_dimensions', 10 );
function remove_thumbnail_dimensions( $html ) {
    $html = preg_replace( '/(width|height)="d*"s/', "", $html );
    return $html;
}

參考文獻

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