LoginSignup
9
8

More than 5 years have passed since last update.

WordPress カスタム投稿タイプに親子関係を持たせる

Posted at

内容

カスタム投稿タイプを作成して記事を親子関係を持たせたい時にどうやるか

ここではプラグインは使いません。

実装手順

function.phpにカスタム投稿タイプを追加する関数を追加します。
その際に、2つのことをやります。

1. 階層構造をtrueにします。


'hierarchical' => true

2. この投稿タイプで「メニューの順序'page-attributes'」を有効にします。

'supports'  => array('title', 'editor', 'thumbnail','page-attributes'),

全体. function.phpに追加したカスタム投稿タイプ


 function create_post_type_organization(){
    $labels= array(
        'name' => 'xxx',
        'all_items' => 'xx',
        'add_new_item' => 'xxを追加',
        'edit_item' => 'xxxを編集',
        'view_item' => 'xxxを表示'
    );
    $args = array(
        'labels'    => $labels,
        'supports'  => array('title', 'editor', 'thumbnail','page-attributes'),
        'public'    => true,
        'show_ui'   => true,
        'menu_position' => 5,
        'has_archive'   => true,
        'hierarchical' => true
    );
    register_post_type('organization', $args);
}
add_action('init', 'create_post_type_organization', 0);

管理画面での表示

追加したカスタム投稿タイプで、親子の設定を入力できるようになります。

スクリーンショット 2018-12-26 8.05.31.png

カスタム投稿タイプ画面での表示

  • アーカイブの表示は「archive-{カスタム投稿タイプ}.php」
  • 個別表示は「single-{カスタム投稿タイプ}.php」

アーカイブ表示  archive-organization.php

ページ一覧を列挙する場合。

<?php while ( have_posts() ) : the_post(); ?>
    <div class="entry-content">
        <a class="link-list" href="<?php the_permalink(); ?>"><?php the_title(); /** タイトル */ ?></a>
    </div>
<?php endwhile; ?>

親子関係で表示する場合

get_childrenで取得

    <div class= "mt-4">
        <?php while ( have_posts() ) : the_post(); 
        if (!$post->post_parent) :?>
            <?php
            $args = array(
                'post_parent' => get_the_ID(),
                'post_status' => 'publish',
                'post_type'   => 'organization'
            );
            $children_array = get_children( $args );
            if ( count( $children_array ) > 0 ) {
                echo '<h3>'.esc_html(get_the_title()).'</h3>';
                echo '<ul class="list-child">';
                foreach ( $children_array as $child ) {
                    $url = get_permalink( $child->ID );

                    $html = '<li>';
                    $html .= '<a href="' . esc_url( $url ) . '">';
                    $html .= esc_html( $child->post_title );
                    $html .= '</a>';
                    $html .= '</li>';

                    echo $html;
                }
                echo '</ul>';
            }else{
                $title = '<h3><a href="' .esc_url(get_permalink()) . '">';
                $title .= esc_html(get_the_title());
                $title .= '</a></h3>';

                echo $title;
            }
            ?>
    <?php endif; 
    endwhile; ?>
    </div>

参考

9
8
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
9
8