WordPress トップや固定ページに指定IDの固定ページ一覧や指定階層の固定ページ一覧を出力する方法

この記事は年前に書かれました。不適当な記述を含む場合がありますので、参考程度に留めてください。

どうもこんばんは。toshikuraです。今回のTipsは【Wordpress トップや固定ページに指定IDの固定ページ一覧や指定階層の固定ページ一覧を出力する方法】です。固定ページ内に指定した複数IDの固定ページを表示したり、全ての固定ページ一覧を表示させる場合に活用できます。投稿のループを記述する【get_posts()】と似た【get_pages()】を使用しますので実装も簡単かと思います。get_posts()に関しては【WordPress タクソノミー、ターム、投稿タイプや著者を特定した記事一覧の出力方法(サムネイル出力含む)】として記事化していますので併せてご参照ください。

固定ページを一覧表示(3件)
<?php global $post;
$args = array(
‘post_type’ => ‘page’,
‘number’ => 3
);
$myposts = get_pages( $args );

foreach( $myposts as $post ) : setup_postdata($post);?>
<?php the_title() ?>
<?php endforeach; ?>

固定ページを古い順に一覧表示
<?php global $post;
$args = array(
‘post_type’ => ‘page’,
‘sort_order’ => ‘desc’,
‘sort_column’ => ‘post_date’
);
$myposts = get_pages( $args );

foreach( $myposts as $post ) : setup_postdata($post);?>
<?php the_title() ?>
<?php endforeach; ?>

固定ページをタイトル順(Z-A)に一覧表示

<?php global $post;
$args = array(
‘post_type’ => ‘page’,
‘sort_order’ => ‘desc’,
‘sort_column’ => ‘post_title’
);
$myposts = get_pages( $args );

foreach( $myposts as $post ) : setup_postdata($post);?>
<?php the_title() ?>
<?php endforeach; ?>

固定ページをID順に一覧表示
<?php global $post;
$args = array(
‘post_type’ => ‘page’,
‘sort_order’ => ‘asc’,
‘sort_column’ => ‘ID’
);
$myposts = get_pages( $args );

foreach( $myposts as $post ) : setup_postdata($post);?>
<?php the_title() ?>
<?php endforeach; ?>

ページID”4″の子階層に所属する固定ページの一覧表示
<?php global $post;
$args = array(
‘post_type’ => ‘page’,
‘sort_order’ => ‘asc’,
‘sort_column’ => ‘ID’,
‘child_of’ => 4
);
$myposts = get_pages( $args );

foreach( $myposts as $post ) : setup_postdata($post);?>
<?php the_title() ?>
<?php endforeach; ?>

ページID12,13を除いた一覧表示
<?php global $post;
$args = array(
‘post_type’ => ‘page’,
‘sort_order’ => ‘asc’,
‘sort_column’ => ‘ID’,
‘child_of’ => 4,
‘exclude’ => ‘12,13’
);
$myposts = get_pages( $args );

foreach( $myposts as $post ) : setup_postdata($post);?>
<?php the_title() ?>
<?php endforeach; ?>

親を指定していますが外してOKです。以降長くなりますので、foreach等の共通部分は割愛します。

ページID2,3,4の一覧表示
$args = array(
‘post_type’ => ‘page’,
‘include’ => ‘2,3,4’
);
カスタムフィールドの内容に応じた固定ページを一覧表示

ここではカスタムフィールド名【名前】に【テスト】が記述されているページの一覧を表示します。

$args = array(
‘post_type’ => ‘page’,
‘meta_key’ => ‘名前’,
‘meta_value’ => ‘テスト’
);
著者別に一覧表示

著者ID【1】の固定ページを一覧で表示する。

$args = array(
‘post_type’ => ‘page’,
‘authors’ => ‘1’
);

ここであげている例以外にも親の状態や公開ステータスによる一覧表示等様々な方法があります。詳しくはget_pages()の関数リファレンスをご参照ください。

以上になります。