LoginSignup
2
1

More than 5 years have passed since last update.

[Wordpress]固定ページに子ページのカスタムフィールドを一覧表示する

Last updated at Posted at 2016-12-04

特定の固定ページに、そのページに所属する子ページのカスタムフィールド値を一覧表示するコードになります。

子ページのカスタムフィールド値を一覧表示する親ページ用のテンプレートファイルを用意します。

親ページのスラッグが 'parent' だとしたら、page-parent.phpというファイルを作成し、以下のコードを記述します。

<?php
    // 子ページ出力のための関数
    $children = get_children(array(
        "post_parent"   => get_the_id(), // このページを親ページとする
        "post_type"     => "page",
        "post_status"   => "publish",
        "order"         => "ASC"
    ));

    // 除外する子ページのスラッグ(配列で複数指定可に)
    $hidden_page_slug = array(
        "hidden1",
        "hidden2"
    );

    foreach($children as $child){

        // 子ページの要素を取得
        $child_title    = $child->post_title; // タイトル
        $child_id       = $child->ID; // ID
        $child_post     = get_page( $child_id );
        $child_slug     = $child_post -> post_name; // スラッグ

        // 表示したいカスタムフィールドの値を取得
        // 配列である必要はありませんが、表示したいフィールドが複数ある場合は便利かと思います
        $arrCf = array(
            "hoge" => get_post_meta($child->ID, "hoge", true),
            "foo" => get_post_meta($child->ID, "foo", true),
            "bar" => get_post_meta($child->ID, "bar", true)
        );

        // 除外する子ページを対象外にする
        if (!in_array($child_slug, $hidden_page_slug)) {

            // ここから一覧表示のためのソース
            echo "<h1>".$child_title."</h1>\n";
            echo "<dl>\n";

            foreach ($arrCf as $key => $value) {
                if ($value != null) {
                    echo "\t<dt>".$key."</dt>\n\t<dd>".$value."</dd>\n\n";
                }
            }
            // $key がカスタムフィールドの名前
            // $value がカスタムフィールドの値

            echo "</dl>\n\n";
            // ここまで

        } // end if
    } // end foreach
?>

これで、このような構造の表示になります。
preview.png

HTMLソースは以下の通り。

<h1>子ページ1</h1>
<dl>
    <dt>hoge</dt>
    <dd>子ページ1のカスタムフィールド'hoge'の値</dd>

    <dt>foo</dt>
    <dd>子ページ1のカスタムフィールド'foo'の値</dd>

    <dt>bar</dt>
    <dd>子ページ1のカスタムフィールド'bar'の値</dd>

</dl>

<h1>子ページ2</h1>
<dl>
    <dt>hoge</dt>
    <dd>子ページ2のカスタムフィールド'hoge'の値</dd>

    <dt>foo</dt>
    <dd>子ページ2のカスタムフィールド'foo'の値</dd>

    <dt>bar</dt>
    <dd>子ページ2のカスタムフィールド'bar'の値</dd>

</dl>

以上です。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1