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

概要説明

ページネーションよりサイトマップページで一覧表示させたいといった時のカスタマイズ。カテゴリー指定、除外機能ありのショートコードでサイトマップページ用の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. WordPress ウィジェットでショートコードを使えるようにする

  2. DBキャッシュ機能を実装 外部データなど任意の情報を一定期間キャッシュさせる

  3. 特定のURLの場合にリダイレクトさせる

サイドバー

よく使うカスタマイズ

最近の記事

アニメの名言集

欲しい物があるなら
何もかもかなぐり捨てて
掴みにいくぐらいの方が
人生は楽しいわよ

彼女、お借りします
by 水原千鶴

Profile

PAGE TOP
Amazon プライム対象