概要説明
ページネーションよりサイトマップページで一覧表示させたいといった時のカスタマイズ。カテゴリー指定、除外機能ありのショートコードでサイトマップページ用のhtml取得ができます。
~ 目次 ~
カテゴリー指定、カテゴリー除外が行えるショートコード
functions.php
/*----------------------------------------------------
サイトマップページのhtmlを取得するショートコード
----------------------------------------------------*/
if ( !function_exists( 'get_sitemap_html' ) ){
function get_sitemap_html( $atts ){
$atts = shortcode_atts( array(
'cat_id' => '0', // 全カテゴリ表示
), $atts, 'sitemap_html' );
$sitemap = '';
// 除外カテゴリ
$exclude = ''; // カンマ区切りで複数指定
//カテゴリー取得
$categories = get_terms( array(
'taxonomy' => 'category',
'include' => array_filter( wp_parse_id_list( $atts['cat_id'] ) ), // 0 は全カテゴリ
'exclude' => array_filter( wp_parse_id_list( $exclude ) ),
'hide_empty' => false,
'orderby' => 'order',
'order' => 'ASC',
) );
if( $categories && !is_wp_error( $categories ) ){
$sitemap = '<div id="sitemap">';
foreach( $categories as $cat ){
//投稿取得 (カテゴリー、件数指定)
$posts = get_posts( array( 'category' => $cat->term_id, 'posts_per_page' => -1 ) );
if( $posts ){
// カテゴリー内に記事データがある場合のみタイトル表示
$sitemap .= '<h3><a href="' . esc_url( get_category_link( $cat->term_id ) ) . '" >' . esc_html( $cat->name ) . '</a></h3>';
// 投稿データ
$sitemap .= '<ul>';
foreach( $posts as $post ){
$sitemap .= '<li><a href="' . esc_url( get_permalink( $post->ID ) ) . '">' . esc_html( get_the_title( $post ) ) . '</a></li>';
}
$sitemap .= '</ul>';
}
}
$sitemap .= '</div>';
}
return $sitemap;
}
add_shortcode( 'sitemap_html', 'get_sitemap_html' );
}
カテゴリ名・記事のタイトルは esc_html、リンクは esc_url で出力します(名前やタイトルに < や ” があっても表示が崩れず、スクリプトも動きません)。
ショートコードの使用例
// 全カテゴリーのサイトマップ表示 [sitemap_html] // カテゴリー指定してのサイトマップ表示 [sitemap_html cat_id=10]
サイトマップショートコードのデモページ
固定ページも出力したい場合
functions.php
$page_include= ''; // 指定ページID(カンマ区切り)
$page_exclude= ''; // 除外ページID(カンマ区切り)
$sitemap .= '<h3>固定ページ</h3>';
$sitemap .= '<ul>';
$sitemap .= wp_list_pages('title_li=&include='.$page_include.'&exclude='.$page_exclude.'&echo=0');
$sitemap .= '</ul>';
return $sitemap; の前に上記を追加で固定ページも出力対象になります。


