LoginSignup
1
1

More than 3 years have passed since last update.

WordPressのAMP対応をLazyLoadと両立

Last updated at Posted at 2020-05-21

WordPressの記事コンテンツをAMP対応するために、いろいろプラグインがありますが、
無料のものだと、なかなかうまくいかず、予期せぬバグが発生したり、デザイン面のカスタマイズができなかったり、
いろいろと厳しい部分があります。
プラグインを使わずに、テンプレートファイルをカスタマイズすれば、意外にも簡単に対応できます。
こちらの記事で詳しく紹介されて、参考させていただきました。
WordPressをプラグインなしでAMP対応させる試み【その1:格闘編】

しかし、Lazyloadを使う場合、画像の一括置換でバッティングしてしまい、うまく動作しません。
そのために、functions.phpの該当箇所を両立できるように対応してみました。
ご参考まで!

functions.php
function add_image_placeholders( $content ) {
    if(isset($_GET['amp']) && is_single()){//ampの場合はampタグに置換
        $content = preg_replace(
        '#<img([^>]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*)>#',
        sprintf( '<amp-img layout="responsive" src="${2}"${3}></amp-img>' ), $content );
        return $content;
    }elseif( is_feed() || is_preview() || ( function_exists( 'is_mobile' ) && is_mobile() ) ){//プレビューやフィードモバイルなどで遅延させない
        return $content;
    }elseif ( false !== strpos( $content, 'data-original' ) ){//既に適用させているところは処理しない
        return $content;
    }else{$content = preg_replace(//Lazyload画像正規表現で置換
        '#<img([^>]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*)>#',//IMGタグの正規表現
        sprintf( '<img${1}src="%s" data-lazy="true" data-original="${2}"${3}><noscript><img${1}src="${2}"${3}></noscript>', get_template_directory_uri().'/images/lazy_image.gif' ),//置換するIMGタグ(JavaScriptがオフのとき用のnoscriptタグも追加)
        $content);//投稿本文(置換する文章)
        return $content;
    }
}
add_filter( 'the_content', 'add_image_placeholders', 99 );
add_filter( 'post_thumbnail_html', 'add_image_placeholders', 11 );

1
1
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
1
1