更新 2019 / 03 / 13

カスタム投稿を追加

functions.phpにコードを追加します。

参考:https://qiita.com/nagasawaaaa/items/9501c0a2e544d85ee78d


                //プランとして追加します。
                add_action( 'init', 'create_post_type' );
                function create_post_type() {
                    register_post_type( 'plan', // 投稿タイプ名の定義
                        array(
                            'labels' => array(
                            'name' => __( 'プラン' ), // フロントで表示する投稿タイプ名
                            'singular_name' => __( 'プランを追加' )
                        ),
                        'public' => true,
                        'menu_position' =>4,
                        'has_archive' => true,
                        'rewrite' => array('with_front' => false),
                        'show_in_rest' => true,
                        'supports' => array('title','editor','thumbnail','page-attributes','custom-fields' )
                        )
                    );
                    /* カテゴリタクソノミー(カテゴリー分け)を使えるように設定する */
                    register_taxonomy(
                        'plan_tax', /* タクソノミーの名前 */
                        'plan', /* 使用するカスタム投稿タイプ名 */
                        array(
                          'hierarchical' => true, /* trueだと親子関係が使用可能。falseで使用不可 */
                          'update_count_callback' => '_update_post_term_count',
                          'label' => 'カテゴリー',
                          'singular_label' => 'カテゴリー',
                          'public' => true,
                          'show_ui' => true,
                          'show_in_rest' => true,
                        )
                      );
                }
                

カスタム投稿をカテゴリー指定で取得

テンプレートにコードを追加します。


               <?php query_posts( array(
                  'post_type' => 'plan', //カスタム投稿名を指定
                  'taxonomy' => 'plan_tax',     //タクソノミー名を指定
                  'term' => 'plan',           //タームのスラッグを指定
                  'posts_per_page' => 3      ///表示件数(-1で全ての記事を表示)
              )); ?>
              <?php if(have_posts()): ?>
              <?php while(have_posts()):the_post(); ?>
                <ul>
                  <li>
                    <a href="<?php the_permalink(); ?>">
                      <h3><?php the_title(); ?></h3>
                      <p><?php the_content();?></p>
                    </a>
                  </li>
                </ul>
              <?php endwhile; else: ?>
               
              ページが存在しない場合の指定
               
              <?php endif; ?>
              <?php wp_reset_query(); ?>