投稿ページのサイトマップをプラグイン無しで実装できるショートコード

概要説明

ページネーションよりサイトマップページで一覧表示させたいといった時のカスタマイズ。カテゴリー指定、除外機能ありのショートコードでサイトマップページ用のhtml取得ができます。

functions.php
/*----------------------------------------------------
 サイトマップページのhtmlを取得するショートコード
----------------------------------------------------*/
if ( !function_exists( 'get_sitemap_html' ) ){

    function get_sitemap_html( $atts ){

        extract( shortcode_atts( array(
           'cat_id' => '0', // 全カテゴリ表示
        ), $atts) );
        $sitemap = '';

        // 除外カテゴリ
        $exclude = ''; // カンマ区切りで複数指定

        //カテゴリー取得
        $categories = get_terms('category','include='.$cat_id.'&hide_empty=false&orderby=order&order=asc&exclude='.$exclude);

        if($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="'.get_category_link($cat->term_id).'" >'.$cat->name.'</a></h3>';

                    // 投稿データ
                    $sitemap .= '<ul>';
                    foreach($posts as $post){
                        $sitemap .= '<li><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';
                    }
                    $sitemap .= '</ul>';
                }
            }
            $sitemap .= '</div>';
        }

        return $sitemap;
    }

    add_shortcode('sitemap_html', 'get_sitemap_html');
}

ショートコードの使用例

// 全カテゴリーのサイトマップ表示
[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; の前に上記を追加で固定ページも出力対象になります。

データベースキャッシュと組み合わせることで表示速度アップ

WordPress Developer Resources

関連機能

  1. 新規記事作成時の初期値設定

  2. ローカル環境構築ツール「Local」でWordPress作業環境を構築 ( Windows,Mac対応 )

  3. WordPress作業にてよく使うChrome拡張機能 作業の効率UP! テーマ、プラグインの調査に大活躍な便利機能

サイドバー

よく使うカスタマイズ

最近の記事

アニメの名言集

当たり前と思われる所にこそ
答えは隠されているものだ

STEINS;GATE
by 岡部 倫太郎

Profile

PAGE TOP
Amazon プライム対象