今の時代、ウェブページは一瞬で表示するべき! 画像の遅延読込に役立つamp-imgの使い方
https://ics.media/entry/18237
この記事を受けて、WordPressの img を amp-img に置き換えたら表示が崩れてしまったのでその対策。
the_content();
となってる箇所を、
$content = str_replace('<img', '<amp-img layout="responsive"', get_the_content());
echo $content;
にする。
//置換前
<img src="sample.png" width="100" height="100" alt="sample" />
//置換後
<amp-img layout="responsive" src="sample.png" width="100" height="100" alt="sample" />
こんなかんじで、 img が amp-img に置き換えられているのだが、 単純に置き換えただけだと、 amp-img に隣接する pとかが画像の裏に回ってしまうらしく幅は可変になるが高さがそのままでアスペクト比が狂ってしまう。 なので、 amp-img を p などで囲むか、 閉じタグをつけなければいけない。
先ほどの置換を少し変えて閉じタグをつけることで回避する。
$content = str_replace('<img (.*) />', '<amp-img \1 layout="responsive"></amp-img>', get_the_content());
echo $content;
//置換前
<img src="sample.png" width="100" height="100" alt="sample" />
//置換後
<amp-img src="sample.png" width="100" height="100" alt="sample" layout="responsive"></amp-img>