WordPressでプラグインを使わずに最低限のサイトマップXMLを生成する

最近、Google Search Consoleで確認すると、なぜかインデックスに登録されていないページがかなり多い印象です…。

WordPressプラグインで生成したサイトマップXMLを送信してはいますが、この情報が多いのが原因なのでは?実は最低限の「投稿・固定ページ」のみ含めておけば良いのでは?

という事で、プラグインも不要、標準の「wp-sitemap.xml」も情報が多いので使わない、とてもシンプルなサイトマップを作ってみました。


最低限のサイトマップを生成する

functions.php」に追記して実行します。

<?php

//---------------------------------------------
//   *サイトマップの自動更新
//---------------------------------------------

//---標準サイトマップを無効化
add_filter('wp_sitemaps_enabled' , '__return_false');

//---投稿や固定ページが更新されるたびに「ib-sitemap.xml」を更新
function update_sitemap() {

	$home_url = home_url();
	$home_lastmod = wp_date('Y-m-d');

	$xml = "<url><loc>{$home_url}</loc><lastmod>{$home_lastmod}</lastmod></url>\n";

	//---固定ページと記事ページを取得
	$posts_ary = get_posts([
		'post_type' => ["page" , "post"] ,
		'posts_per_page' => -1 ,
		'post_status' => "publish" ,
		'orderby' => "modified" ,
		'order' => "DESC"
	]);

	if($posts_ary){

		foreach($posts_ary as $post){

			$url = get_the_permalink($post->ID);
			$lastmod = get_the_modified_date("Y-m-d" , $post->ID);
			$xml .= "<url><loc>{$url}</loc><lastmod>{$lastmod}</lastmod></url>\n";
		}
	}


	$sitemap = <<<HERE
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{$xml}</urlset>
HERE;

	//---ファイルを書き出し
	file_put_contents(get_theme_file_path() . "/ib-sitemap-1.xml" ,  $sitemap , LOCK_EX);

	//---------------------------------------------
	//   *サイトマップインデックス生成
	//---------------------------------------------

	$sitemap_url = get_stylesheet_directory_uri() . "/ib-sitemap-1.xml";

$sitemap_index = <<<HERE
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>{$sitemap_url}</loc><lastmod>{$home_lastmod}</lastmod></sitemap>
</sitemapindex>
HERE;

	//---ファイルを書き出し
	file_put_contents(get_theme_file_path() . "/ib-sitemap.xml" ,  $sitemap_index , LOCK_EX);
}

add_action('save_post', 'update_sitemap');


サイトマップの生成例

https://www.kojinteki.net/wp-content/themes/ib-child/kojinteki.latest/ib-sitemap.xml

https://www.kojinteki.net/wp-content/themes/ib-child/kojinteki.latest/ib-sitemap-1.xml

テーマの関係でこの例では深い階層にファイルが生成されていますが、テーマフォルダの直下に「ib-sitemap.xml」「ib-sitemap-1.xml」が生成されます。「ib-sitemap.xml」までのURLをGoogle Search Consoleに登録するとよいでしょう!