自力でAMP化。一から自作テーマを作り直してAMP対応に
今回、AMP化プラグインを使わず、自力で一からテーマを作り、AMPに対応させました。
テーマ本体を書き換えるだけでなく、使用しているプラグインもAMP化させる必要がある為、莫大な作業が必要でした。
そもそも『AMP化』は、AMP化プラグインを使ってできるほど簡単な話じゃありません。
サーチコンソールで十数回もの再チェックを行い、修正に修正を重ねて、やっと全てのページでOKが出ました。
それくらい、想定外のエラーが頻発します。
これから自力でAMP化しようと思ってる人は、覚悟して取り掛かった方がいいです。
かなり大変です。
ただ、要所となるコードをこの記事に記載しておきますので、ぜひ参考にしてみてください。
AMP化する前に必要なこと(ローカルのテスト環境を整える)
AMP化に着手する前に、XAMPP等を使い、必ずローカル上でWordpressのテスト環境を用意してください。
サーバー上で可動している状態でのAMPテストは絶対に不可能です。
コードエラーで画面が表示されなくなるという危険もありますし、キャッシュが残ってしまうので、正確な表示を確認できず、無駄な時間を費やすことになります。
AMP化の目次
- function.php
- header.php(ヘッダー)
- index.php(記事一覧・検索ページ兼用)
- single.php/page.php(記事・固定ページ)
- comments.php(コメント投稿フォーム)
- searchform.php(検索フォーム)
- .htaccessでAMPトップページのリダイレクト
AMP化のコード
「function.php」に記載するコード
AMP判定
URLに「amp=1」と付いたパラメーターが送信されたときにAMPのコードを表示する。
例:https://www.ore-server.com/blog/?p=652&=1
// AMPチェック
function amp_check() {
	$myAmp = false;
	$string = $post->post_content;
	if($_GET['amp'] === '1'){
	    $myAmp = true;
	}
	return $myAmp;
}
メインコンテンツをAMP用に変換
single.phpなどの記事ページで、表示するメインコンテンツ「the_content()」の中身をAMP用に書き換えます。
amp-imgでは画像サイズの記載が必要となる為、ファイル名からメディアライブラリ内を探して画像サイズを取得しています。
もしメディアライブラリ内に画像が見つからない場合は、WordPressの仕様上、ファイル名に画像サイズが記載してあるので、ファイル名から正規表現で画像サイズを取得しています。
//AMP用にコンテンツを変換する
function convert_amp($the_content){
 
    // AMPのパラメーターがないときは戻る
    if (!amp_check()) {
    return $the_content;
    }
    // C2A0文字コード(UTF-8の半角スペース)を通常の半角スペースに置換
    $the_content = str_replace('\xc2\xa0', ' ', $the_content);
    
    // imgタグの置換
    $img_pattern = '/<img [^>]*?src="(https?:\/\/[^"]+?)"[^>]*?>/iu';
    preg_match_all($img_pattern,$the_content,$img_matches);
    // imgタグにhttp:が付いていないと検知できないので、必ず画像ファイルにはhttpsをつけること
    foreach ($img_matches[1] as $img_key => $img_val) {
        $rep_flag = 0;
     
        // wordpressが自動挿入する画像サイズの除去
        // 画像IDの取得
        $img_id = attachment_url_to_postid($img_val);
        // 画像サイズの取得
        $img_src = wp_get_attachment_image_src($img_id,'full');
        
        // メディアアップローダーにある画像の処理
        if($img_src[1]) {
            
            // 画像altの取得
            $img_alt = get_post_meta($img_id,'_wp_attachment_image_alt', true);
            
            // 画像サイズ
            $img_width = $img_src[1];
            $img_height = $img_src[2];
            
            // AMP対応imgタグに変更
            $img_chg = '<amp-img layout="responsive" src="'.$img_val.'" width="'.$img_width.'" height="'.$img_height.'" alt="'.$img_alt.'">';
            
            $rep_flag = 1;
        } else {
                // メディアアップローダーにない画像の処理
                preg_match_all('/-([^-]*)(?:.jpg|.png|.gif)/',$img_matches[1][$img_key], $size_match);
            
                // 画像サイズ情報がある場合のみ処理
                if ($size_match[1][0]) {
                    
                    // 画像サイズ情報の取得
                    list($img_width,$img_height) = explode("x",$size_match[1][0]);
                    // altから画像情報の取得
                    preg_match('/(alt)=("[^"]*")/i',$img_matches[0][$img_key],$img_alt);
                    $img_alt = str_replace("\"", "", $img_alt[2]);
                
                    // AMP対応imgタグに変更
                    $img_chg = '<amp-img layout="responsive" src="'.$img_val.'" width="'.$img_width.'" height="'.$img_height.'" alt="'.$img_alt.'">';
                    
                    $rep_flag = 1;
                }
        }
        if($rep_flag) {
            // スラッシュや特殊文字のエスケープ
            $img_quote = preg_quote($img_matches[0][$img_key],'/');
            // コンテンツの中身を変更
            $the_content = preg_replace("/$img_quote/",$img_chg, $the_content);
            
        }    
    }
    // style属性を取り除く
    $the_content = preg_replace('/ +style=["][^"]*?["]/i', '', $the_content);
    $the_content = preg_replace('/ +style=[\'][^\']*?[\']/i', '', $the_content);
    // target属性を取り除く
    $the_content = preg_replace('/ +target=["][^"]*?["]/i', '', $the_content);
    $the_content = preg_replace('/ +target=[\'][^\']*?[\']/i', '', $the_content);
    // onclick属性を取り除く
    $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);
    // YouTubeを置換する(埋め込みコード)
    $pattern = '/<iframe.+?src="https:\/\/www.youtube.com\/embed\/(.+?)(\?feature=oembed)?".*?><\/iframe>/is';
    $append = '<amp-youtube layout="responsive" data-videoid="$1" width="800" height="450"></amp-youtube>';
    $the_content = preg_replace($pattern, $append, $the_content);
    // iframeを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);
    
    //ブログカードの不要な記述削除
    $the_content = preg_replace('/ security=["][^"]*?["]/i', '', $the_content);
    $the_content = preg_replace('/ marginwidth=["][^"]*?["]/i', '', $the_content);
    $the_content = preg_replace('/ marginheight=["][^"]*?["]/i', '', $the_content);
    // AMP用twitterタグ置換
    $tw_pattern = '/https:\/\/twitter.com\/.+?.\/status\/(\w+)+?\?/iu';
    preg_match_all($tw_pattern,$the_content,$tw_matches);
    // twitterタグ削除
    $pattern = '/<blockquote class="twitter-tweet".+?.<\/script>/is';
    $append = '<amp-twitter layout="responsive" width=600 height=600 data-tweetid="'.$tw_matches[1][0].'"></amp-twitter>';
    $the_content = preg_replace($pattern, $append, $the_content);
    
    // スクリプトを除去する
    $pattern = '/<script.+?<\/script>/is';
    $append = '';
    $the_content = preg_replace($pattern, $append, $the_content);
    return $the_content;
}
add_filter('the_content','convert_amp', 999999999);
コメント部分をAMP化
// AMP用に個別コメント返信機能を変換する
function convert_comment($comment_reply_link){
    if (!amp_check()) {
        return $comment_reply_link;
    }
    // onclick属性を取り除く
    $comment_reply_link = preg_replace( '/ *?onclick=["][^"]*?["]/i', '', $comment_reply_link );
    $comment_reply_link = preg_replace( '/ *?onclick=[\'][^\']*?[\']/i', '', $comment_reply_link );
    
    return $comment_reply_link;
}
add_filter('comment_reply_link','convert_comment', 999999999);
// コメント本文の呼び出し
function mytheme_comments($comment, $args, $depth){
   $GLOBALS['comment'] = $comment; ?>
   <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
     <div id="comment-<?php comment_ID(); ?>" class="comments-wrapper">
         
       <!-- コメント本文 -->
       <div class="comments-content">
           <?php
             $commentID_parent = $comment->comment_parent;
             if( $commentID_parent != 0 ):
           ?>
             <span class="replay_target"><?php echo get_comment_author($commentID_parent); ?>さんへの返信</span>
           <?php else: ?>
             <!-- <a href="#top">「<?php the_title(); ?>」へのコメント</a> -->
           <?php endif; ?>
           <?php 
             if ($comment->comment_approved == '0') {
               echo '<span class="comments-approval">※このコメントは承認待ちです。</span>';
             }
           ?>
         <?php comment_text() ?>
       </div>
         
       <div class="comments-meta">
       <?php echo get_avatar( $comment, $args['avatar_size']) ?>
         <ul class="comments-meta-list">
           <li class="comments-author-name">
           <?php printf('<cite class="fn">%s</cite>', get_comment_author_link()) ?>
           </li>
           <li class="comments-date">
             <?php printf(__('%1$s at %2$s'), get_comment_date(), get_comment_time()) ?>
           </li>
         </ul>
       </div>
       <div class="comments-reply">
         <?php comment_reply_link(array_merge( $args, array(
            'reply_text'=>'返信する', 
            'add_below' =>$add_below, 
            'depth' =>$depth, 
            'max_depth' =>$args['max_depth']))) 
         ?>
       </div>
     </div>
     <!-- comment-comment_ID -->
   <?php
}
header.php(ヘッダー)
AMP HTML宣言
// AMP
if (amp_check()) {
    echo '<html amp>'."\n";
} 
// HTML
else {
    echo '<html lang="ja">'."\n";
}
構造化データ
AMPでは必ず構造化データの記載が必要です。
// トップページ
if(is_home()) {
    echo '<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# website: http://ogp.me/ns/website#">'."\n";
}
// トップページ以外
else {
   echo '<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#">'."\n";
}
echo "\n";
echo '  <meta charset="utf-8">'."\n";
// サムネイル画像情報の取得
$thumbnail_id = get_post_thumbnail_id();
$eye_img = wp_get_attachment_image_src( $thumbnail_id , 'large' );
// 構造化(description)
if(is_home()) {
    echo '  <meta name="thumbnail" content="'.get_bloginfo('template_url').'/images/eye_img.jpg">'."\n";
    $cons_eye_img = get_bloginfo('template_url').'/images/eye_img.jpg';
    $cons_eye_height = 675;
    $cons_eye_width = 1200;
    $cons_desc = get_bloginfo('description');
}
else {
    echo '  <meta name="thumbnail" content="'.$eye_img[0].'">'."\n";
    $cons_eye_img = $eye_img[0];
    $cons_eye_height = $eye_img[1];
    $cons_eye_width = $eye_img[2];
    $cons_desc = get_post_meta($post->ID,'description',true);
}
?>  <script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "<?php echo wp_get_document_title() ?>",
        "image": {
            "@type": "ImageObject",
            "url": "<?php  echo $cons_eye_img; ?>",
            "height": <?php  echo $cons_eye_height; ?>,
            "width": <?php  echo $cons_eye_width; ?>
        },
        "datePublished": "<?php echo get_the_date('c'); ?>",
        "dateModified": "<?php echo get_the_modified_date('c'); ?>",
        "author": {
            "@type": "Person",
            "name": "Taro Yamada"
        },
        "publisher": {
            "@type": "Organization",
            "name": "<?php bloginfo('name'); ?>",
            "logo": {
            "@type": "ImageObject",
                "url": "<?php echo bloginfo('template_url').'/images/amp_logo.jpg'; ?>",
                "width": 452,
                "height": 66
            }
        },
        "description": "<?php echo $cons_desc; ?>"
    }
  </script>
<?php 
AMP専用モジュールの読み込み
// AMPヘッダー
if(amp_check()) {
    
    echo '  <link rel="canonical" href="<?php echo $canonical_url; ?>">'."\n";
    echo '  <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>'."\n";
    echo '  <script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>'."\n";
    echo '  <script async src="https://cdn.ampproject.org/v0.js"></script>'."\n";   
    echo '  <script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>'."\n";
    echo '  <script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>'."\n";
    echo '  <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>'."\n";
    echo '  <script async custom-element="amp-twitter" src="https://cdn.ampproject.org/v0/amp-twitter-0.1.js"></script>'."\n";
}
ヘッダーのAMP化・CSS読み込み
AMPでは外部ファイルの読み込みができないので、ヘッダーにそのまま表示させます。
// AMP
if(amp_check()) {
    echo "\n";
	echo '  <title>'.wp_get_document_title().'</title>'."\n";
    echo "\n";
	echo '  <style amp-custom>'."\n";
	/* テーマのCSS読み込み */
	echo file_get_contents(get_template_directory() .'/style.css');
    
	echo '  </style>'."\n";
    echo "\n";
    /* ログイン時に表示されるメニューバー */
	if (is_user_logged_in()) {
		_admin_bar_bump_cb();
    }
    
    echo '  <script async custom-element="amp-ad" src="https://cdn.ampproject.org/v0/amp-ad-0.1.js"></script>'."\n";
}
// HTML
else {
?>
<?php if(is_home()) { ?>
    <link rel="amphtml" href="<?php echo $canonical_url.'?amp=1'; ?>">
<?php } else { ?>
    <link rel="amphtml" href="<?php echo $canonical_url.'&=1'; ?>">
<?php } ?>
    <link rel="stylesheet" href="<?php bloginfo( 'stylesheet_url' ); ?>">
<?php 
      wp_head();
}
Google AnalyticsのAMP化
Google Analyticsの解析タグは、非AMPは<head>内、AMP用は<body>の直後に記載します。
// HTML用
if(!amp_check()) {
?>  <script>
	  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
	  ga('create', 'UA-xxxxxxx-xx', 'auto');
	  ga('send', 'pageview');
	</script>
<?php } 
echo '</head>'."\n"; ?> <body>
// AMP用
<?php if (amp_check()) { // AMP用 Google Analytics ?>
    <amp-analytics type="gtag" data-credentials="include">
    <script type="application/json">
    {
      "vars" : {
        "gtag_id": "UA-xxxxxxx-xx",
        "config" : {
          "UA-xxxxxxx-xx": { "groups": "default" }
        }
      }
    }
    </script>
    </amp-analytics>
<?php } ?>
index.php(記事一覧・検索ページ兼用)
<?php get_header(); ?>
    <!-- 記事ヘッダー -->
    <div class="inner">
    <div id="h1_title_bar">
    <?php if (is_home() ) : // カテゴリページ・投稿一覧ページにカテゴリメニューを表示 ?>
        <h1>最新記事</h1>
    <?php elseif (is_date()): ?>
        <h1><?php echo get_the_date('Y年n月'); ?></h1>
    <?php elseif (is_category() || is_tag()): ?>
        <h1><?php single_tag_title(); ?></h1>
    <?php elseif (is_search()): ?>
        <?php
        global $wp_query;
        $total_results = $wp_query->found_posts;
        $search_query = get_search_query();
        ?>
        <h1>検索結果:<?php echo $search_query; ?><span>(<?php echo $total_results; ?>件)</span></h1>
    <?php endif; ?>
        
    </div>
                
    <?php if( is_search() && $total_results == 0 ): ?>
        <div id="search_box">
            「<?php echo $search_query; ?>」に一致する情報は見つかりませんでした。
        </div>
    <?php else : ?>
        <?php if (have_posts()) : ?>
            <ul class="article_list">
            <?php while (have_posts()) : the_post(); ?>
                <li>
                    <div class="article_img">
                <?php /* サムネイル有 */ ?>
                <?php if(has_post_thumbnail()) : ?>
                    <?php
                    $thumbnail_id = get_post_thumbnail_id();
                    $eye_img = wp_get_attachment_image_src( $thumbnail_id , 'large' );
                    $eye_alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
                    ?>
                    <a href="<?php the_permalink() ?>">
                    <?php /* AMP */ ?>
                    <?php if(amp_check()): ?>
                        <?php echo '<amp-img src="'.$eye_img[0].'" width="'.$eye_img[1].'" height="'.$eye_img[2].'" alt="'.$eye_alt.'" layout="responsive">'; ?>
                    <?php /* HTML */ ?>
                    <?php else: ?>
                        <?php the_post_thumbnail('thumbnail') ?>
                    <?php endif; ?>
                    </a>
                <?php /* サムネイル無 */ ?>
                <?php else : ?>
                    <?php $noimge = get_bloginfo('template_url').'/images/noimage.jpg'; ?>
                    <a href="<?php the_permalink() ?>">
                    <?php /* AMP */ ?>
                    <?php if(amp_check()): ?>
                                                    <?php echo '<amp-img src="'.$eye_img[0].'" width="300" height="300" alt="noimage" layout="responsive">'; ?>
                    <?php /* HTML */ ?>
                    <?php else: ?>
                                                    <?php echo '<img src="'.$noimge.'" alt="noimage">'; ?> 
                    <?php endif; ?>
                    </a>
                <?php endif; ?>
                    </div>
                    <div class="article_title">
                        <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
                        <span class="date"><?php the_time('Y年m月d日') ?></span>
                    </div>
                </li>
            <?php endwhile; ?>
            </ul>
            <?php
            if ( function_exists( 'pagination' ) ) :
                pagination( $wp_query->max_num_pages, get_query_var( 'paged' ) );
            endif;
            ?>
        <?php else : ?>
            <div class="error_page">
                <h2 class="title">記事が見つかりませんでした。</h2>
                    <p>検索で見つかるかもしれません。</p>
                    <?php get_search_form(); ?>
            </div>
        <?php endif; ?>
        
    <?php endif; ?>
    </div>
<?php get_footer(); ?>
single.php/page.php(記事・固定ページ)
メインコンテンツ
<?php get_header(); ?>
<!-- 記事ヘッダー -->
<?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
        <article>
            
            <div class="inner"> 
                <dl class="update">
                <?php if(get_the_time('Y/m/d') != get_the_modified_date('Y/m/d')) { ?>
                    <dt>最終更新日</dt>
                    <dd><time datetime="<?php echo the_modified_date('Y-m-d'); ?>"><?php the_modified_date('Y年n月j日') ?></time></dd>
                <?php } ?>
                <dt>記事公開日</dt>
                <dd><time datetime="<?php echo the_time('Y-m-d'); ?>"><?php the_time('Y年n月j日') ?></time></dd>
                </dl>
                <div id="h1_title">
                    <h1><?php the_title(); ?></h1>
                </div>
            </div>
            <!-- 記事本文 -->
            <div class="article_body">
                <div class="inner">
                    <?php the_content(); ?>
                </div>
            </div>
        </article>
        <?php comments_template(); ?>
    <?php endwhile; ?>
<?php else : ?>
    <div class="inner">
        
        <!-- エラー -->
        <div class="error_page">
            <h2 class="title">記事が見つかりませんでした。</h2>
            <p>検索で見つかるかもしれません。</p>
            <?php get_search_form(); ?>
        </div>
        
    </div>
<?php endif; ?>
                
<?php get_footer(); ?>
おすすめ記事
    <!-- おすすめ記事 -->
    <?php 
    $RecIDs[0] = 3171;
    $RecIDs[1] = 4512;
    $RecIDs[2] = 4049;
    $RecIDs[3] = 2046;
    $RecIDs[4] = 4117;
    $Recs = array(
        'post__in' => $RecIDs,
        'orderby' =>  'post__in'
    );
    $my_query = new WP_Query($Recs);
                
    if( $my_query->have_posts() ) { ?>
        <div class="relate">
            
            <h3 class="relate_title">オススメの人気記事</h3>
            
            <div class="relate_bg">
                <?php echo '<ul class="article_list">';
                while ($my_query->have_posts()) : $my_query->the_post(); ?>
                    <li>
                        <div class="article_img article_rank">
                            <a href="<?php the_permalink();?>">
                                <?php //サムネイル画像(無い場合は別の画像)を表示
                                if ( get_the_post_thumbnail($post->ID,'thumbnail') ):
                                    if(!amp_check()) {
                                        echo wp_get_attachment_image(the_post_thumbnail('thumbnail')); 
                                    }
                                    else {
                                        $thumbnail_id = get_post_thumbnail_id();
                                        $eye_img = wp_get_attachment_image_src( $thumbnail_id , 'large' );
                                        $eye_alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
                                        echo '<amp-img layout="responsive" src="'.$eye_img[0].'" width="'.$eye_img[1].'" height="'.$eye_img[2].'" alt="'.$eye_alt.'">';
                                    }
                                else:
                                    if(!amp_check()) {
                                        echo '<img src="'.get_bloginfo('template_url').'/images/noimage.jpg" alt="Noimage">';
                                    }
                                    else {
                                        echo '<amp-img layout="responsive" src="'.get_bloginfo('template_url').'/images/noimage.jpg" width="1200" height="675" alt="Noimage">';
                                    }
                                endif;
                                ?>
                            </a>
                        </div>
                        <div class="article_title">
                            <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
                            <span class="date"><?php the_time('Y年m月d日') ?></span>
                        </div>
                    </li>
                <?php
                endwhile;
                wp_reset_query();
                echo '</ul>'; ?>
                
            </div>
        </div>
    <?php } // if $my_query ?>
タグ関連記事
タグに関連する記事を表示します。
カテゴリの関連記事は、他の方のブログでたくさん書いてあるので、そちらを見て下さい。
    <!-- タグ関連記事 -->
    <?php 
    
    // 同じタグを持つ記事を取得
    $tags = wp_get_post_tags($post->ID);
    $tagIDs = array();
    if ($tags):
    $tagcount = count($tags);
        for ($i = 0; $i < $tagcount; $i++) {
            $tagIDs[$i] = $tags[$i]->term_id;
        }
        $args = array(
            'orderby' => 'date',
            'tag__in' => $tagIDs,
            'post__not_in' => array($post->ID), // 現在の記事を含めない
            'posts_per_page' => 5,
            'ignore_sticky_posts' => true // true:先頭固定表示の投稿を無視
        );
        $my_query = new WP_Query($args);
        if( $my_query->have_posts() ) { ?>
            <!-- 関連記事 -->
            <div class="relate">
                
                <h3 class="relate_title"><?php the_tags( '','・','' ); ?>に関連する他の記事</h3>
                
                <div class="relate_bg">
                    <?php echo '<ul class="article_list">';
                    while ($my_query->have_posts()) : $my_query->the_post(); ?>
                        <li>
                            <div class="article_img">
                                <a href="<?php the_permalink();?>">
                                    <?php //サムネイル画像(無い場合は別の画像)を表示
                                    if ( get_the_post_thumbnail($post->ID,'thumbnail') ):
                                        if(!amp_check()) {
                                            echo wp_get_attachment_image(the_post_thumbnail('thumbnail')); 
                                        } else {
                                            $thumbnail_id = get_post_thumbnail_id();
                                            $eye_img = wp_get_attachment_image_src( $thumbnail_id , 'large' );
                                            $eye_alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
                                            echo '<amp-img layout="responsive" src="'.$eye_img[0].'" width="'.$eye_img[1].'" height="'.$eye_img[2].'" alt="'.$eye_alt.'">';
                                        }
                                    else:
                                        if(!amp_check()) {
                                            echo '<img src="'.get_bloginfo('template_url').'/images/noimage.jpg" alt="Noimage">';
                                        }
                                        else {
                                            echo '<amp-img layout="responsive" src="'.get_bloginfo('template_url').'/images/noimage.jpg" width="1200" height="675" alt="Noimage">';
                                        }
                                    endif;
                                    ?>
                                </a>
                            </div>
                            <div class="article_title">
                                <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
                                <span class="date"><?php the_time('Y年m月d日') ?></span>
                            </div>
                        </li>
                    <?php
                    endwhile;
                    wp_reset_query();
                    echo '</ul>'; 
                    ?>
                    <div class="more_cate">
                        <?php 
                          $category = get_the_category(); 
                          if ( $category[0] ) {
                            echo '<a href="' . get_category_link( $category[0]->term_id ) . '">「' . $category[0]->cat_name . '」カテゴリの記事を見る</a>';
                          }
                        ?>
                    </div>
                </div>
            </div>
        <?php } // if $my_query ?>
                
    <?php endif; ?>
新着記事
<ul>
<?php global $g_entry_count; //グローバル変数の呼び出し?>
<?php query_posts('posts_per_page='.$g_entry_count); //クエリの作成?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li class="new-entry">
  
  <div class="new-entry-thumb">
      
                    <a href="<?php the_permalink();?>">
      
                    <?php 
                    if (get_the_post_thumbnail($post->ID,'thumbnail')) {
                        if(!amp_check()) {
                            echo wp_get_attachment_image(the_post_thumbnail('thumbnail')); 
                        }
                        else {
                            $thumbnail_id = get_post_thumbnail_id();
                            $eye_img = wp_get_attachment_image_src( $thumbnail_id , 'large' );
                            $eye_alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
                            echo '<amp-img layout="responsive" src="'.$eye_img[0].'" width="'.$eye_img[1].'" height="'.$eye_img[2].'" alt="'.$eye_alt.'">';
                        }
                    } else {
                        
                        if(!amp_check()) {
                            echo '<img src="'.get_bloginfo('template_url').'/images/noimage.jpg" alt="Noimage">';
                        }
                        else {
                            echo '<amp-img layout="responsive" src="'.get_bloginfo('template_url').'/images/noimage.jpg" width="1200" height="675" alt="Noimage">';
                        }
      
                    }
                    ?>
                        
                    </a>
      
  </div><!-- /.new-entry-thumb -->
  
  <div class="new-entry-content">
                    <span class="date"><?php the_time('Y年m月d日') ?></span>
    <a href="<?php the_permalink(); ?>" class="new-entry-title"><?php the_title();?></a>
  </div><!-- /.new-entry-content -->
 
</li><!-- /.new-entry -->
<?php endwhile; 
else :
  echo '<p>新着記事はありません。</p>';
endif; ?>
<?php wp_reset_query(); ?>
</ul>
comments.php(コメント投稿フォーム)
<?php
  if (post_password_required()) {
     return;
   }
?>
<!-- comments start -->
<div class="inner">
    
   <?php if (have_comments()) :?>
    
        <?php
        $commentcount = get_comments( array(
          'status' => 'approve',
          'post_id'=> get_the_ID(), 
          'type'=> 'comment', 
          'count' => true
        ) );
        ?>
       <h3 id="com_cnt"><?php echo $commentcount.' 件のコメント'; ?></h3>
       <!-- comments-list start -->
       <ul class="comments-list">
         <?php wp_list_comments(array(
           'style'=>'ul',
           'type'=>'comment',
           'callback'=>'mytheme_comments'
          )); ?>
       </ul>
       <?php if (get_comment_pages_count() > 1) : ?>
           <ul class="comments-nav">
             <li class="comments-prev"><?php previous_comments_link('<< 前のコメント'); ?></li>
             <li class="comments-next"><?php next_comments_link('次のコメント >>'); ?></li>
           </ul>
       <?php endif; ?>
    
  <?php endif; ?>
  <!-- comments-list end -->
  <!-- comments-form start -->
    
    <?php if(!amp_check()) { ?>
        <div class="hidden_box">
            <input type="checkbox" id="label1"/>
            <?php if (have_comments()) { ?>
                <label for="label1" class="label_text">コメント投稿</label>
                <div>
            <?php } else { ?>
                <label for="label1" class="label_text label_on">コメント投稿フォーム</label>
                <div class="hidden_show">
            <?php } ?>
                    <?php
                     $comments_args = array(
                       'fields' => array(
                       'author' => '<p class="comments-form-author">' . '<label for="author">' . __( 'Name' ) . ( $req ? ' <span class="comments-required">*</span>' : '' ) . '</label>' .'<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '"></p>',
                       'email' => '<p class="comments-form-email"><label for="email">' . __( 'Email' ) . ( $req ? ' <span class="comments-required">*</span>' : '' ) . '</label> ' .'<input id="email" name="email" type="email"' . ' value="' . esc_attr( $commenter['comment_author_email'] ) . '"></p>'
                     ),
                     'title_reply' => '',
                     'comment_notes_before' => '<p class="comments-notes">メールアドレスは公開されませんのでご安心ください。また、<span class="comments-required">*</span> が付いている欄は必須項目となります。</p>',
                     'comment_notes_after' => '<p class="comments-form-allowed-tags">内容に問題なければ、下記の「コメントを送信する」ボタンを押してください。</p>',
                     'label_submit' => 'コメントを送信する',
                    );
                    comment_form($comments_args);
                    ?>
                    <!-- comments-form end -->
                </div>
        </div>
    <?php } ?>
    
</div>
<!-- comments end -->
searchform.php(検索フォーム)
<?php if (!amp_check()) { ?>
<div id="search">
	<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
		<label class="hidden" for="s">
			<?php __( '', 'default' ); ?>
		</label>
		<input type="text" placeholder="検索するテキストを入力" value="<?php the_search_query(); ?>" name="s" id="s" />
		<input type="image" src="<?php echo get_template_directory_uri(); ?>/images/search.png" alt="検索" id="searchsubmit" />
	</form>
</div>
<?php } else { ?>
<?php } ?>
「.htaccess」でAMPトップページのリダイレクト
サーチコンソールで「URL が見つかりませんでした(404)」とAMPのエラーが表示されることがあります。
原因は、AMPページのTOPページが「https://www.ore-server.com/blog/&=1」と認識されてしまうことです。
.htaccessで「https://www.ore-server.com/blog/?amp=1」へリダイレクトしてください。
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^blog&=1 https://www.ore-server.com/blog?amp=1 [R=301,L] </IfModule>
これで終わりです。
パーツごとにコピペすれば一応動きます。
カスタムしてお使い下さい。

