WordPress/サイトマップを作る
WordPressで、プラグインを使わずにサイトマップを作成する。
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');
サイトマップの固定ページを作成
[sitemap]
と記入するだけ。