0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPressのアイキャッチでlazysizesを使用する

Posted at

はじめに

PageSpeed Insightsでwebサイトのスピードチェック・改善点探しをする人も多いと思います。

その中の改善できる項目で「オフスクリーン画像の遅延読み込み」というのがありまして、WordPressのプラグインを使う方が多いと思います。
が、「lazysizes」という画像遅延読み込みのjsのライブラリを使う方もいると思いますので、アイキャッチで画像遅延読み込みを適用する方法を書いておきます。

lazysizesの使い方

  1. jsのライブラリを読み込む
  2. 画像のclassにlazyloadをつける
  3. 画像のパスはdata-src="sample.png"にする

方法

アイキャッチ画像を取得するときに、lazyloadクラスをつける

$thumbnailAttr = [
    'class' => 'lazyload',
    'alt' => 'サンプルです',
];
$thumbnailTag = get_the_post_thumbnail($post_id, [160, 84], $thumbnailAttr);

echo $thumbnailTag;

get_the_post_thumbnail

hookを利用して、出力されるsrcをsrc-dataに置き換える

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

function my_post_image_html( $html, $post_id, $post_image_id ) {

    //遅延読み込み対象の画像のみ
    if(strpos($html, 'lazyload') === false) {
        return $html;
    }

    //srcをdata-srcに置換する
    $html = str_replace('src="', 'data-src="', $html);
    return $html;
}

post_thumbnail_html

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?