sitemap.xml を細かくカスタムしたい。プラグインでは対応していないかゆいところをなんとかしたい。
というケースが多々あったのでいまはこちらのコードをfunctions.phpに入れてテンプレとして使っています。
SEO対策的にも経験上sitemap.xmlをちゃんと作るとしっかりとindexされていきます。
getのlinkだけではクローラーは全部辿ってくれません。。(ページ数が膨大なサイトは特に)
functions.php
//--------------------------- SiteMap関連 ---------------------------------------------//
add_action('publish_post', 'create_sitemap'); //記事更新時
add_action('publish_page', 'create_sitemap'); //固定ページ更新時
add_action('post_updated', 'create_sitemap'); //投稿または固定ページが更新された後に実行する
add_action('deleted_post', 'create_sitemap'); //投稿またはページが削除された直後に実行する
/**
* Custom Sitemap
*
* @author tuti
*/
function create_sitemap()
{
// 投稿、カスタム投稿、固定ページのデータを取得
$sitemap_posts = get_posts(array(
'numberposts' => -1, // 全件
'orderby' => 'modified', // 更新日順
'post_type' => array('post', 'page', 'info', 'studio', 'models'), // ページ、投稿、カスタム投稿
'post_status' => 'publish',
'order' => 'DESC' // 降順
));
// 除外するページID
$no_publish_pages = array(128, 126, 205, 42);
$sitemap_data = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$sitemap_data .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
// xml文字列生成
foreach($sitemap_posts as $post)
{
setup_postdata($post);
if ( ! in_array($post->ID, $no_publish_pages) )
{
$postdate = explode(" ", $post->post_modified);
$sitemap_data .= '<url>'."\n".
'<loc>'. get_permalink($post->ID) .'</loc>'."\n".
'<lastmod>'. $postdate[0] .'</lastmod>'."\n".
'<changefreq>monthly</changefreq>'."\n".
'</url>'."\n";
}
}
//sitemap.xmlを出力
file_put_contents(ABSPATH . "sitemap_comp.xml",$sitemap_data);
}
ニュースサイトやニュースアプリ連携の際にフィードをカスタムしたり、プラグインが吐き出してるページをsitemapに入れたいとか色々あるわけなので
サイトマップはコードで管理した方が自由度があがりオススメです 😀