Display Images With Native Lazy Loading In WordPress.jpg

使用Native Lazy Loading顯示WordPress文章圖片

WordPress 5.5版內建圖片Lazy-loading和Sitemap功能,預設開啟。提供自訂函式範例,可實現延遲載入、響應式圖片等效果。使用時只需呼叫函式並傳入圖片ID即可。

更新

WordPress5.5版在2020年8月11日公佈,裡面內建了圖片Lazy-loading功能,且此設定預設為開啟,因此並不需要再手動修改程式碼,此版本也首次將Sitemap變成內建功能。詳細內容請見〈WordPress 5.5 Field Guide〉。Native Lazy Loading Responsive Images in WordPress

來吧,複製貼上

function custom_the_post_thumbnail($image_id){
	$image_url = wp_get_attachment_url($image_id);
	$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
	$image_srcset = wp_get_attachment_image_srcset($image_id);
	$return = '<img class="w-100" src="'.$image_url.'" srcset="'.$image_srcset.'" loading="lazy" alt="'.$image_alt.'">';
	echo $return;
}

範例應用

while ( have_posts() ) {
  the_post();
  $image_id = get_post_thumbnail_id(); ?>
  <div class="">
    <?php custom_the_post_thumbnail($image_id); ?>
  </div>
  <?php
}

🚀 以每年 5 美元解鎖無廣告體驗

✓ 14 天免費試用 ✓ 隨時取消

在〈使用Native Lazy Loading顯示WordPress文章圖片〉中有 1 則留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *