WordPressテーマを作成していて、ショートタグで子ページ一覧を表示しようとした時に使った関数とコードを書いておく。
get_the_ID()
固定ページのIDを取得するのに使用した。
関数リファレンス/get the ID - WordPress Codex 日本語版
get_page_children()
親ページで子ページの一覧を取得する際に使用した。
関数リファレンス/get page children - WordPress Codex 日本語版
wp_strip_all_tags()
投稿データ(固定ページ)からHTMLを削除した抜粋を取得するのに使用した。
関数リファレンス/wp strip all tags - WordPress Codex 日本語版
日本語の切り出し
日本語にような2バイト文字はsubstr()
で切り出そうとすると◆の様な文字列が出てしまい上手く切り出せない。この場合、mb_substr()
を使うことで上手く切り出すことが出来る。なお、日本語は2バイトであるため第二引数には、切り出したい文字数/2
を指定する必要がある。今回はthe_excerpt()
のデフォルトである110文字を参考に55
を指定した。
ショートタグでの出力
原則としてショートタグでの出力はecho
やprint
を使わない方が良い。出力は結合して最後にreturn
で返すのが標準的な手法のよう。
php - Wordpress using echo vs return in shortcode function - Stack Overflow
/*
* Enable short-tag
* * * * * * * * * * * * * * * * * * * * * * */
function get_child_list($argv) {
// 固定ページでない場合は終了
if(!is_page()) {
return "Error: Not supported type(only page).";
}
// クエリの組み立て
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array(
'post_type' => 'page',
'nopaging' => 'true'
));
// 子ページの取得
$child_pages = get_page_children( get_the_ID(), $all_wp_pages );
// 子ページが無い場合
if(count($child_pages)<1){
return;
}
// デバッグ用
// echo "<pre>".var_dump($child_pages)."</pre>";
// HTMLの組み立て
$child_pages_html = '<ul class="childList">';
// それぞれの子ページに対して処理を実行(ループ)
foreach($child_pages as $child_page){
// 子ページのデータを取得
$child_page_id = $child_page->ID;
$child_page_data = get_post($child_page_id);
$child_page_title = $child_page_data->post_title;
$child_page_raw_content = $child_page_data->post_content;
// HTMLタグを除去して110文字(日本語は2バイト文字)を取得
$child_page_content = mb_substr(wp_strip_all_tags($child_page_raw_content, true), 0, 55);
$child_page_url = $child_page_data->guid;
// HTMLの組み立て
$child_pages_html .= <<< EOF
<li><a href="$child_page_url">
<span>$child_page_title</span>
<div>$child_page_content</div>
</a></li>
EOF;
} // end of foreach
// 組み立てたHTMLを返す
return "$child_pages_html</ul>";
} // end of get_child_list()
add_shortcode('child_list', 'get_child_list');
このコードをfunctions.php
へ書いて[child_list]
を固定ページで書くと、サイトでは子ページ一覧が表示される。
Copyright (c) 2017 Tomoyuki KOYAMA
Released under the MIT license
http://opensource.org/licenses/mit-license.php