2026年9月27日

2026年9月27日

WordPressにAMP(Accelerated Mobile Pages)を実装してモバイル表示を高速化する方法

はじめに

AMP(Accelerated Mobile Pages)はGoogleが推進するモバイルページ高速化フレームワークで、適切に実装することでモバイル検索結果でのTop Storiesカルーセル表示・Core Web Vitals改善・直帰率の低下が期待できます。WordPress公式AMPプラグインを活用し、カスタムテンプレートとバリデーション対策を組み合わせた実装方法を解説します。

症状・原因

  • モバイルページの読み込みが遅く、Core Web VitalsのLCPが改善できない
  • AMPページを作成したがバリデーションエラーが多発してGoogleに認識されない
  • カスタムJavaScriptやサードパーティスクリプトがAMPと互換性がなく表示が崩れる

解決手順

ステップ1:公式AMPプラグインのセットアップとバリデーションを確認する

WordPressの公式AMPプラグインをインストールし、動作モードを設定します。

# WP-CLI でAMPプラグインをインストールする
wp plugin install amp --activate

# AMPが有効化されているか確認する
wp plugin status amp

# 全投稿のAMPバリデーションを一括実行する(初回設定後に実行)
wp amp validation run --force
<?php
// functions.php に追加 ─ AMPプラグインの動作設定

// AMPのデフォルトモードを設定する
// Standard: 全ページAMP / Transitional: AMP版を並行提供 / Reader: ?amp=1で切り替え
add_filter( 'amp_pre_get_option_theme_support', function() {
    return 'transitional'; // 通常版とAMP版を並行して提供するモード
} );

// 特定の投稿タイプのみAMPを有効にする
add_filter( 'amp_supportable_post_types', function( $post_types ) {
    // 通常投稿とカスタム投稿タイプ'news'のみAMPを有効にする
    return [ 'post', 'news' ];
} );

// 特定のカテゴリーではAMPを無効にする
add_filter( 'amp_skip_post', function( $skip, $post_id ) {
    // 「広告」カテゴリーはAMP非対応のため無効にする
    if ( has_category( 'advertisement', $post_id ) ) {
        return true; // trueを返すとAMPをスキップする
    }
    return $skip;
}, 10, 2 );

ステップ2:カスタムAMPテンプレートディレクトリを設定する

テーマ内にAMP専用テンプレートを作成し、ブランドに合わせたデザインを適用します。

<?php
// functions.php に追加 ─ カスタムAMPテンプレートの設定

// AMPテンプレートをテーマ内のカスタムディレクトリから読み込む
add_filter( 'amp_template_dir', function( $dir ) {
    // テーマの amp/ ディレクトリをテンプレートディレクトリとして使用する
    return get_template_directory() . '/amp/';
} );

// AMPページ用のカスタムスタイルを追加する
add_action( 'amp_post_template_css', function() {
    // AMP CSS は50KBの上限があるため最小限に抑える
    ?>
    /* カスタムAMPスタイル ─ インラインでのみ記述可能 */
    body {
        font-family: 'Noto Sans JP', sans-serif;
        background: #ffffff;
        color: #1d2327;
        margin: 0;
        padding: 0;
    }

    .amp-header {
        background: #0073aa;
        padding: 12px 16px;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 100;
    }

    .amp-header a {
        color: #ffffff;
        text-decoration: none;
        font-weight: bold;
        font-size: 18px;
    }

    .amp-content {
        max-width: 800px;
        margin: 60px auto 0;
        padding: 16px;
    }

    /* AMPでは外部フォントをlink要素で読み込む必要がある */
    <?php
} );

ステップ3:amp_post_template_metadataフィルターでJSON-LDをカスタマイズする

AMPページの構造化データ(JSON-LD)をフィルターで拡張し、リッチリザルトを最適化します。

<?php
// functions.php に追加 ─ AMPのJSON-LDカスタマイズ

add_filter( 'amp_post_template_metadata', function( $metadata, $post ) {
    // 著者情報を詳細化する
    $metadata['author'] = [
        '@type' => 'Person',
        'name'  => get_the_author_meta( 'display_name', $post->post_author ),
        'url'   => get_author_posts_url( $post->post_author ),
        // 著者画像をJSON-LDに追加する(Gravatar使用)
        'image' => [
            '@type'  => 'ImageObject',
            'url'    => get_avatar_url( $post->post_author, [ 'size' => 96 ] ),
            'width'  => 96,
            'height' => 96,
        ],
    ];

    // パブリッシャー情報(サイト情報)を追加する
    $metadata['publisher'] = [
        '@type' => 'Organization',
        'name'  => get_bloginfo( 'name' ),
        'logo'  => [
            '@type'  => 'ImageObject',
            // AMPのロゴ画像は600x60px以内・横長画像が推奨される
            'url'    => get_template_directory_uri() . '/images/amp-logo.png',
            'width'  => 600,
            'height' => 60,
        ],
    ];

    // 記事のキーワードを構造化データに追加する
    $tags = get_the_tags( $post->ID );
    if ( $tags ) {
        $metadata['keywords'] = implode( ', ', wp_list_pluck( $tags, 'name' ) );
    }

    return $metadata;
}, 10, 2 );

ステップ4:AMP固有コンポーネントを実装する(amp-img・amp-video・amp-analytics)

AMP HTMLでは通常のHTMLタグの代わりにAMP専用コンポーネントを使用する必要があります。

<?php
// functions.php に追加 ─ AMP互換コンポーネントへの自動変換

// imgタグをamp-imgに変換するフィルター(AMPページのみ)
add_filter( 'the_content', function( $content ) {
    if ( ! function_exists( 'is_amp_endpoint' ) || ! is_amp_endpoint() ) {
        return $content; // AMPページ以外には適用しない
    }

    // imgタグをamp-imgに変換する(widthとheight属性が必須)
    $content = preg_replace_callback(
        '/<img([^>]+)>/i',
        function( $matches ) {
            $attrs = $matches[1];

            // srcとsizeが取得できない場合はスキップする
            if ( ! preg_match( '/src=["\']([^"\']+)["\']/i', $attrs, $src_match ) ) {
                return $matches[0];
            }

            // widthとheightがない場合はデフォルト値を設定する
            if ( ! preg_match( '/width=["\']?\d+["\']?/i', $attrs ) ) {
                $attrs .= ' width="800"';
            }
            if ( ! preg_match( '/height=["\']?\d+["\']?/i', $attrs ) ) {
                $attrs .= ' height="450"';
            }

            // amp-img は layout="responsive" で画面幅に合わせてリサイズされる
            $attrs .= ' layout="responsive"';

            return '<amp-img' . $attrs . '></amp-img>';
        },
        $content
    );

    return $content;
}, 20 );
<!-- AMP テンプレート内での各コンポーネントの使用例 -->

<!-- AMP画像: layout="responsive"で画面幅に合わせた表示 -->
<amp-img
    src="/path/to/image.jpg"
    width="800"
    height="450"
    layout="responsive"
    alt="記事のアイキャッチ画像">
</amp-img>

<!-- AMP動画: poster属性でサムネイルを設定する -->
<amp-video
    src="/path/to/video.mp4"
    poster="/path/to/poster.jpg"
    width="800"
    height="450"
    layout="responsive"
    controls>
</amp-video>

<!-- AMP用アナリティクス: 通常のGAタグは使用不可 -->
<amp-analytics type="gtag" data-credentials="include">
<script type="application/json">
{
    "vars": {
        "gtag_id": "G-XXXXXXXXXX",
        "config": {
            "G-XXXXXXXXXX": { "groups": "default" }
        }
    }
}
</script>
</amp-analytics>

ステップ5:AMP Validatorでバリデーションを行い一般的なエラーを修正する

AMPバリデーションエラーの種類と修正方法を実装します。

# AMP Validator CLIをインストールする
npm install -g amphtml-validator

# ページのAMPバリデーションを実行する
amphtml-validator https://example.com/sample-post/?amp=1

# 結果例:
# PASS: https://example.com/sample-post/?amp=1
# または
# FAIL: ... <script> tags with custom JavaScript are not allowed in AMP documents.
<?php
// functions.php に追加 ─ 一般的なAMPバリデーションエラーの修正

// エラー1: カスタムJavaScriptの除去(AMPではインラインJSは禁止)
add_filter( 'the_content', function( $content ) {
    if ( ! function_exists( 'is_amp_endpoint' ) || ! is_amp_endpoint() ) {
        return $content;
    }

    // AMPページではscriptタグ(type指定なし・onClickイベント等)を除去する
    $content = preg_replace( '/<script\b(?![^>]*type=["\']application\/(ld\+json|json)["\'])[^>]*>.*?<\/script>/is', '', $content );

    // インラインイベントハンドラーを除去する(onclick・onmouseoverなど)
    $content = preg_replace( '/\s+on(?:click|mouseover|mouseout|load|focus|blur)=["\'][^"\']*["\']/i', '', $content );

    // styleタグをamp-custom内で処理できるよう除去する(!importantも禁止)
    $content = preg_replace( '/<style[^>]*>.*?<\/style>/is', '', $content );

    return $content;
}, 99 ); // 他のフィルターが処理した後に実行する

// エラー2: amp-mustacheなどの必要なコンポーネントを条件付きで読み込む
add_filter( 'amp_post_template_data', function( $data ) {
    // amp-carousel コンポーネントを追加する(複数画像の記事で使用する場合)
    $data['amp_component_scripts']['amp-carousel'] =
        'https://cdn.ampproject.org/v0/amp-carousel-0.1.js';

    return $data;
} );

注意事項

  • AMP廃止の動向: Googleは2021年にAMPをTop Storiesの必須要件から除外しました。Core Web Vitalsのスコアが良ければAMPなしでも上位表示が可能です。実装コストを考慮した上で導入を判断してください
  • AMPキャッシュURL: GoogleはAMPページを https://example-com.cdn.ampproject.org/ にキャッシュします。canonical URLとAMP URLのhreflang設定を忘れずに行うこと
  • CSSの50KB制限: AMPのスタイルシートは50KBまでに制限されています。Critical CSSのみをインラインに含め、それ以外はserver-side renderingで対応すること

まとめ

WordPressへのAMP実装は公式AMPプラグインを基盤とし、カスタムテンプレート・JSON-LD最適化・AMP固有コンポーネントへの変換・バリデーションエラーの修正という4ステップで進めることが重要です。関連記事:WordPressをPWA対応してオフライン閲覧とプッシュ通知を実装する方法

お気軽にご相談ください

お見積りへ お問い合わせへ
▲