サイトマップを自動生成して検索エンジンに送信する方法

サイト運営において、検索エンジンにページを正しく認識させるためにはサイトマップが重要です。
WordPressでは、プラグインやPHPコードを使って自動生成し、検索エンジンに送信することができます。

実装のポイント

  • サイトマップを自動生成して常に最新状態を保つ
  • 検索エンジンに送信してSEO効果を高める
  • プラグインを使わずに自作コードでも生成可能

functions.php にコードを追加


// ------------------------------
// XMLサイトマップ自動生成
// ------------------------------
function my_generate_sitemap() {
    $posts = get_posts(array(
        'numberposts' => -1,
        'post_type'   => array('post','page','news'),
        'post_status' => 'publish'
    ));

    header('Content-Type: application/xml; charset=utf-8');
    echo '';
    echo '';

    foreach($posts as $post) {
        $permalink = get_permalink($post->ID);
        $modified  = get_the_modified_time('c', $post->ID);
        echo '';
        echo '' . esc_url($permalink) . '';
        echo '' . esc_html($modified) . '';
        echo '';
    }

    echo '';
    exit;
}

// /sitemap.xml で自動生成
add_action('init', function() {
    if($_SERVER['REQUEST_URI'] === '/sitemap.xml') {
        my_generate_sitemap();
    }
});

// サイトマップURL取得
function get_sitemap_url() {
    return home_url('/sitemap.xml');
}

// 投稿公開・更新時に検索エンジンに通知
function notify_search_engines($post_id, $post = null) {
    if(get_post_status($post_id) !== 'publish') return;

    $allowed_types = array('post','page','news');
    $post_type = get_post_type($post_id);
    if(!in_array($post_type, $allowed_types)) return;

    $sitemap_url = urlencode(get_sitemap_url());

    wp_remote_get('http://www.google.com/ping?sitemap=' . $sitemap_url);
    wp_remote_get('http://www.bing.com/webmaster/ping.aspx?siteMap=' . $sitemap_url);
}

// 投稿公開・更新時に通知
add_action('publish_post', 'notify_search_engines', 10, 2);
add_action('publish_page', 'notify_search_engines', 10, 2);
add_action('publish_news', 'notify_search_engines', 10, 2);
add_action('post_updated', 'notify_search_engines', 10, 2);
  
補足:
- 上記コードは「post」「page」「news」のみを対象にXMLサイトマップを生成します。
- 必要に応じてカスタム投稿タイプを配列に追加してください。

代用プラグイン

  • Google XML Sitemaps:サイトマップ自動生成と検索エンジン送信対応
  • Yoast SEO:SEO全般に加え、サイトマップ生成も対応
  • All in One SEO Pack:サイトマップ作成・送信が簡単に行える

まとめ

サイトマップを自動生成することで、検索エンジンにページを正しく認識させ、SEO効果を高めることができます。
プラグインを使う方法も簡単ですが、PHPコードで自作することで柔軟にカスタマイズ可能です。