WordPress本文のAMP化 置換処理

構築・開発
<?php
  // 本文を取得
  $the_content  = do_shortcode($post->post_content);
  
  // C2A0文字コード(UTF-8の半角スペース)を通常の半角スペースに置換
  $the_content = str_replace('\xc2\xa0', ' ', $the_content);
  
  // style/target/onclickを取り除く
  $the_content = preg_replace('/ +style=["][^"]*?["]/i', '', $the_content);
  $the_content = preg_replace('/ +style=[\'][^\']*?[\']/i', '', $the_content);
  $the_content = preg_replace('/ +target=["][^"]*?["]/i', '', $the_content);
  $the_content = preg_replace('/ +target=[\'][^\']*?[\']/i', '', $the_content);
  $the_content = preg_replace('/ +onclick=["][^"]*?["]/i', '', $the_content);
  $the_content = preg_replace('/ +onclick=[\'][^\']*?[\']/i', '', $the_content);
  
  // FONTタグを取り除く
  $the_content = preg_replace('/<font[^>]+?>/i', '', $the_content);
  $the_content = preg_replace('/<\/font>/i', '', $the_content);
  
  // 画像タグをAMP用に置換
  $the_content = preg_replace('/<img/i', '<amp-img layout="responsive"', $the_content);
  
  // iframe(YouTubeリンク)をamp-youtubeに置換する
  $pattern = '/(<iframe)(.*)(youtube.com\/embed\/)([a-zA-Z0-9]*)\"(.*)<\/iframe>/i';
  $append = '<amp-youtube layout="responsive" width="425" height="240" data-videoid="$4"></amp-youtube>';
  $the_content = preg_replace($pattern, $append, $the_content);
  
  // iframe(YouTube以外)をamp-iframeに置換する
  $pattern = '/<iframe/i';
  $append = '<amp-iframe layout="responsive"';
  $the_content = preg_replace($pattern, $append, $the_content);
  $pattern = '/<\/iframe>/i';
  $append = '</amp-iframe>';
  $the_content = preg_replace($pattern, $append, $the_content);
  
  //スクリプトを除去する
  $pattern = '/<script.+?<\/script>/is';
  $append = '';
  $the_content = preg_replace($pattern, $append, $the_content);
?>

amp-youtubeやamp-iframeがある場合は、専用のJavascriptをロードする必要がありますので、変換処理を行った後のhead内に下記を入れてください。

<?php
    if(strpos($the_content,'amp-youtube') !== false){
        echo '<script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>';
    }
    
    if(strpos($the_content,'amp-iframe') !== false){
        echo '<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>';
    }
?>

参考

https://www.ampproject.org/docs/reference/components/amp-iframe

コメント

スポンサーリンク
タイトルとURLをコピーしました