tamakipedia

フロントエンドエンジニア。Typescriptもう特訓中です。一日の振り返りや学んだことをちょっとずつ吐いています。

【amp】AMP HTML タグの属性で指定されたレイアウトが無効です。

記事内のimgタグをamp-imgタグに変換した際に起こったエラーについて。

今回行ったこと

preg_replaceを用いて、
imgタグをamp-imgタグに置き換える。

            //<img>を<amp-img>に差し替え
            $content = preg_replace('/<img (.*?)>/i', '<amp-img layout="responsive" $1></amp-img>', $content);
            $content = preg_replace('/<img (.*?) \/>/i', '<amp-img layout="responsive" $1></amp-img>', $content);

エラー内容

調べてみると複数の記事で、width と height が設定されていないページがあったために起きたエラーでした。
(500記事くらいがエラー起こしてて放心状態でした、、)

f:id:okinawanpizza:20210714141303p:plain

解決方法

preg_match_allで全てのamp-imgコンポーネントを取得、
widthとheightが設定されていなければ、サイズを 16:9 で追加するという処理を加える。

functions.php に下記のコードを追加


            //<img>を<amp-img>に差し替え
            $content = preg_replace('/<img (.*?)>/i', '<amp-img layout="responsive" $1></amp-img>', $content);
            $content = preg_replace('/<img (.*?) \/>/i', '<amp-img layout="responsive" $1></amp-img>', $content);

            //以下を追記

            //imgタグに横幅、縦幅を付与
            preg_match_all('/<amp-img(.*?)<\/amp-img>/i', $content, $tw_matches);
            foreach ($tw_matches[0] as $index => $tw_match_tag) { 
              $matchimgwithoutwidth = preg_match('/width=(.*?)/',$tw_matches[0][$index]);
              $matchimgwithoutheight = preg_match('/height=(.*?)/',$tw_matches[0][$index]);
              if(!$matchimgwithoutwidth && !$matchimgwithoutheight){
                $replaceString = preg_replace('/<amp-img(.*?)<\/amp-img>/i','<amp-img width="400" height="300" $1</amp-img>',$tw_matches[0][$index]);
                $pattern = $tw_matches[0][$index];
                $replace = $replaceString;
                $content = str_replace($pattern, $replace, $content);
              }
            }

メモ

phpのforeach文でインデックスを取得する → foreach ( $array as $index => $value )の形で実装可能

<?php
 $array = array( '学校', '公園', '自宅', '商店' );
 foreach ( $array as $index => $value ) {
  echo $index. ":". $value. "\n";
 }
?>

// 出力結果
0:学校
1:公園
2:自宅
3:商店

参考:
https://designsupply-web.com/media/knowledgeside/5900/

幅はとりあえず 400 x 300 で設定しています。
もし画像のサイズがphp側で取得可能であれば、
取得した数字を使います。
できるのかな。、、 https://pisuke-code.com/php-how-to-get-image-size/

おしまい