wp_list_pages()で指定項目数ごとにリストを分割する
wp_list_pages()
で指定項目数ごとにリストを分割するには、まずテーマのfunctions.phpに下記のように記載します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/** * 指定項目数(separate_count)ごとにリストを分割します。 */ class Walker_Page_Separeted extends Walker_Page { private $separate_count; private $count = 0; private $running_count = 0; public function __construct($separate_count = 10) { $this->separate_count = $separate_count; } public function start_el( &$output, $page, $depth = 0, $args = array(), $current_page = 0 ) { // 指定項目数ごとに<ul>を追加します。 if ($this->running_count != 0 && $this->running_count % $this->separate_count == 0) { $output .= "<ul>"; } parent::start_el($output, $page, $depth, $args, $current_page); } public function end_el( &$output, $page, $depth = 0, $args = array() ) { parent::end_el($output, $page, $depth, $args); // depth(階層)がトップレベルの時だけ項目数をカウントし、指定項目数ごとに</ul>を追加します。 if ($depth == 0) { $this->running_count++; if ($this->count != $this->running_count && $this->running_count % $this->separate_count == 0) { $output .= "</ul>"; } } } function walk( $elements, $max_depth ) { $args = func_get_args(); // ※ walk_page_tree() 内で実際には上の引数以外にも$rと$current_pageが渡ってきます。 $r = $args[2]; $current_page = $args[3]; // トップレベルの項目数をカウントします。(最後に</ul>を付けないようにするため) foreach($elements as $element) { if($r['child_of'] == $element->post_parent) $this->count++; } return parent::walk( $elements, $max_depth ); } } |
次に出力したいテンプレートのファイル内(home.phpなど)に下記のように記載します。('walker'の行以外のパラメータは自由に追加・変更して下さい)
1 2 3 4 5 6 7 8 9 |
<ul> <?php // 3つごとにリストを分割(数を変更したい場合は下記の「3」を必要な数に変更) wp_list_pages(array( 'title_li' => '', 'walker' => new Walker_Page_Separeted(3) )); ?> </ul> |
上記のパラメータの場合、下記のように出力されます。(test 3とtest 4の間に</ul><ul>が入っていることが確認できると思います)
1 2 3 4 5 6 7 8 9 10 11 |
<ul> <li class="page_item page-item-xxx"><a href="http://xxx">test 1</a></li> <li class="page_item page-item-xxx"><a href="http://xxx">test 2</a> <ul class="children"> <li class="page_item page-item-xxx"><a href="http://xxx">test 2-1</a></li> </ul> </li> <li class="page_item page-item-xxx"><a href="http://xxx">test 3</a></li> </ul><ul><li class="page_item page-item-xxx"><a href="http://xxx">test 4</a></li> <li class="page_item page-item-xxx"><a href="http://xxx">test 5</a></li> </ul> |