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

広告WordPress・PHP を学べる本

Amazonのアソシエイトとして、WordPress functions.phpは適格販売により収入を得ています。

概要説明

ページネーションよりサイトマップページで一覧表示させたいといった時のカスタマイズ。カテゴリー指定、除外機能ありのショートコードでサイトマップページ用の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; の前に上記を追加で固定ページも出力対象になります。

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

WordPress Developer Resources

関連機能

  1. WordPress パンくずリスト表示用のショートコード

  2. アイキャッチ画像の設定機能を追加したい場合

  3. WordPress のメニューのリンクに title 属性を付ける:nav_menu_link_attributes で安全に足す

サイドバー

よく使うカスタマイズ

最近の記事

Profile

PAGE TOP