この記事には広告を含む場合があります。
記事内で紹介する商品を購入することで、当サイトに売り上げの一部が還元されることがあります。
WordPressでサイトマップを設定する場合、PS Auto Sitemapなどの便利なプラグイン
がありますが、負荷の原因となるプラグインはなるべく避けたいところです。
PHPで簡単に設定できますので紹介します。
- サイトマップとは
-
ホームページ・ブログなどのサイト内のページ構成を一覧できるようにした案内ページ。
webサイト内のページ構成の明確化によるユーザビリティの向上。
検索エンジンクローラーの巡回補助としての役目もありSEO対策にも繋がります。
固定ページにて下記のようにサイトマップ用のページを作成します。
固定ページで作成したサイトマップを表示するためのPHPファイルを作成します。
下記を「functions.php」内に追加。
/*サイトマップ*/
//カテゴリーと投稿をツリー構造で取得(引数:親カテゴリID, カテゴリーのulタグの表示フラグ)
function getCategoryAndPostTree($parent_id = 0, $cat_ul_use_flag = 1){
$numberposts = 20; //投稿の表示件数
$return = "";
//カテゴリー取得
$categories = get_terms('category','parent='.$parent_id.'&hide_empty=0&orderby=order&order=asc');
if($categories){
if($cat_ul_use_flag == 1) $return .= "<ul>\n";
foreach($categories as $category_values){
$return .= '<li><a href="'.get_category_link($category_values->term_id).'" >'.$category_values->name."</a>\n";
//投稿取得
add_filter('pre_option_category_children', 'my_category_children');
$posts = get_posts(array('numberposts'=>$numberposts, 'category'=>$category_values->term_id));
remove_filter('pre_option_category_children', 'my_category_children');
$arg_ul_use_flag = 1;
if($posts){
$return .= "<ul>\n";
foreach($posts as $post_values){
$return .= '<li><a href="'.get_permalink($post_values->ID).'">'.$post_values->post_title."</a></li>\n";
}
$arg_ul_use_flag = 0;
}
$return .= getCategoryAndPostTree($category_values->term_id, $arg_ul_use_flag);
if($posts) $return .= "</ul>\n";
$return .= "</li>\n";
}
if($cat_ul_use_flag == 1) $return .= "</ul>\n";
}
return $return;
}
//サブカテゴリに所属する投稿記事を排除する
function my_category_children( $return ) {
return array();
}
//サイトマップ
function simple_sitemap(){
global $wpdb;
echo '<div id="sitemap">';
//カテゴリと投稿のツリー
$get_category_and_post .= getCategoryAndPostTree(0);
echo $get_category_and_post;
//固定ページのツリー
$args = array('depth' => 0,
'show_date' => NULL,
'date_format' => get_option('date_format'),
'child_of' => 0,
'exclude' => NULL,
'include' => NULL,
'title_li' => '',
'echo' => 1,
'authors' => NULL,
'sort_column' => 'menu_order, post_title',
'link_before' => NULL,
'link_after' => NULL,
'exclude_tree' => NULL );
echo '<ul>';
wp_list_pages($args);
echo '</ul>';
echo '</div>';
}
add_shortcode('sitemap', 'simple_sitemap');
32ARTS 
