DamienKarrus’s blog

プログラミングとクライミングの足跡

固定ページの親ページにて、子ページの一覧を出力する方法

親ページの用意

固定ページで親ページをつくる。slugをたとえばeventlistとする

page.phpをコピーしてpage-eventlist.phpをつくる。

slugを指定するとそのページのテンプレートはpage-[入力されたslug].phpとなる

 

親ページの記述

一覧表示ページ(親ページ)にて、子ページを取得してwhileのループでタイトルに<a>タグをつけて、本文から抜粋(defaultは先頭110文字)を取得して表示する。
the_title():タイトル表示
the_permalink():リンク表示
get_the_excerpt():本文取得

<ul>
<?php
    $cp=damien_get_child_pages();//サブクエリで子供たちを取得する関数を作成
    if($cp->have_posts()):
        while($cp->have_posts()): $cp->the_post();
?>

<li>
<div>
<a href="<?php the_permalink();?>">
<p><?php the_title();?></p></a>
<p><?php echo get_the_excerpt();?></p>
</div>
</li>
<?php
        endwhile;
        wp_reset_postdata();
    endif;
?>
</ul>

functions.phpに関数追加

サブクエリで子供たちを取得する関数

子ページの情報を取得するクエリを発行し、取得したwpオブジェクトをreturnする
get_the_ID():現在表示中のページのIDを取得
posts_per_page:取得するページ数、-1なら全てのページ

function damien_get_child_pages($number = -1,$specified_id = null){
    if(isset($specified_id)):
        $parent_id=$specified_id;
    else:
        $parent_id=get_the_ID();
    endif;
    $args=array(
            'posts_per_page'=> $number,
            'post_type'=>'page',
            'orderby'=>'menu_order',
            'order'=>'ASC',
            'post_parent'=>$parent_id,
        );
    $child_pages = new WP_Query($args);
    return $child_pages;
}