目錄
原始文章
顯示WordPress文章圖片,並使用Native Lazy Loading
更新
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
}