【WordPress】カスタム投稿タイプの使い方。カスタムポストの登録・表示・出力方法、カスタムタクソノミーの使用例など

カスタム投稿タイプの使い方。カスタムポストの登録・表示・出力方法、カスタムタクソノミーの使用例など

WordPressではデフォルトの投稿以外にも、カスタムポストを使用して投稿タイプの追加やカスタマイズすることができます。

テンプレート階層
テンプレート階層

デフォルトの投稿は、

  • 投稿ページ:「single.php」
  • アーカイブページ:「archive.php」や「home.php」

を使用しますが、カスタムポストは

  • カスタムポストの投稿ページ:「single-$posttype.php
  • カスタムポストのアーカイブページ:「archive-$posttype.php

を使用します。

今回はこのポートフォリオサイトの制作実績を載せるページ「Works」で、実際に実装したカスタムポストを例に使用します。

なので、

  • functions.php
  • single-works.php
  • archive-works.php

の3つphpファイルを使用します。

カスタム投稿タイプの登録

functions.php

//カスタム投稿タイプの登録
add_action('init', function () {
  register_post_type('works', [
    'label' => 'Web制作',
    'public' => true,
    'menu_position' => 5,
    'menu_icon' => 'dashicons-laptop',
    'supports' => ['thumbnail', 'title', 'editor', 'custom-fields'],
    'has_archive' => true,
    'show_in_rest' => true,
  ]);
  register_taxonomy('genre', 'works', [
    'label' => '制作ジャンル',
    'hierarchical' => true,
  ]);
  register_taxonomy_for_object_type('genre', 'works');
  register_taxonomy_for_object_type('category', 'works'); // カテゴリー
  register_taxonomy_for_object_type('post_tag', 'works'); // タグ
});

functions.phpに上記のコードを記述すれば、管理画面にカスタムポストが追加されます。

WordPress管理画面
WordPress管理画面

register post type

  register_post_type('works', [
    'label' => 'Web制作',
    'public' => true,
    'menu_position' => 5,
    'menu_icon' => 'dashicons-laptop',
    'supports' => ['thumbnail', 'title', 'editor', 'custom-fields'],
    'has_archive' => true,
    'show_in_rest' => true,
  ]);
  • works → 自由に設定
  • ‘label’ → 管理画面に表示させるラベル名
  • ‘public’ → パブリックにするかどうか
  • ‘menu_position’ → 管理画面メニューの表示位置(5は投稿の下)
  • ‘menu_icon’ → ラベルのアイコン(設定しなくてもOK)
  • ‘supports’ → 投稿できる項目(初期値はtitleとeditor)
  • ‘has_archive’ → アーカイブページを有効にするかどうか
  • ‘show_in_rest’ → この投稿タイプを RESTAPI に含めるかどうか。投稿タイプをブロックエディタで使用できるようにするにはこれを true に設定する。

詳しく知りたい方はこちらのページを参考に。
関数リファレンス/register post type

メニューアイコンを設定したい方はこちらのページを参考に。
Developer Resources: Dashicons

register taxonomy

カスタム投稿タイプにカスタムタクソノミー(カスタム分類)を登録。

  register_taxonomy('genre', 'works', [
    'label' => '制作ジャンル',
    'hierarchical' => true,
  ]);
  register_taxonomy_for_object_type('genre', 'works');
  register_taxonomy_for_object_type('category', 'works'); // カテゴリー
  register_taxonomy_for_object_type('post_tag', 'works'); // タグ
  • ‘genre’ → 自由に設定
  • ‘works’ → 上記のregister post typeで設定したものと同じものを記述
  • ‘label’ → 管理画面に表示させるラベル名
  • ‘hierarchical’ → true ならカテゴリーのような階層あり(子を持つ)タクソノミー
  • register_taxonomy_for_object_type(‘genre’, ‘works’); は設定したものを記述
  • register_taxonomy_for_object_type(‘category’, ‘works’)とregister_taxonomy_for_object_type(‘post_tag’, ‘works’)は必要であれば記述

詳しく知りたい方はこちらのページを参考に。
関数リファレンス/register taxonomy

カスタム投稿タイプの表示・出力

single-works.php

      <?php /***** メインループ開始 *****/ ?>
      <?php if (have_posts()) : ?>
        <?php while (have_posts()) : the_post(); ?>
          <div class="Post_taxonomies">
            <?php
            $taxonomy = 'genre';
            $terms = get_the_terms($post->ID, $taxonomy);
            ?>
            <?php foreach ($terms as $term) : ?>
              <?php echo $term->name; ?>
            <?php endforeach; ?>
          </div>
          <div class="Post_date">
            <i class="fa-solid fa-clock"></i> <?php the_time(get_option('date_format')); ?>
            <?php
            if (
              get_the_time(get_option('date_format')) !=
              get_the_modified_date()
            ) :
            ?>
              <i class="fa-solid fa-clock-rotate-left"></i> <?php the_modified_date(); ?>
            <?php endif; ?>
          </div>

          <h1 class="Post_title smoothTrigger"><?php the_title(); ?></h1>

          <figure class="figure">
            <?php if (has_post_thumbnail()) : ?>
              <?php the_post_thumbnail('full'); ?>
            <?php endif; ?>
          </figure>

          <div class="content">
            <?php the_content(); ?>
          </div>

          <div class="btnBox">
            <a class="btn -type1" href="<?php echo esc_url(home_url('/works/')); ?>">READ MORE IN WORKS</a>
          </div>
        <?php endwhile; ?>
      <?php endif; ?>
      <?php /***** メインループ終了 *****/ ?>
            <?php
            $taxonomy = 'genre';
            $terms = get_the_terms($post->ID, $taxonomy);
            ?>
            <?php foreach ($terms as $term) : ?>
              <?php echo $term->name; ?>
            <?php endforeach; ?>

デフォルトの投稿でカテゴリーを表示させるときは、「get_categories」「get_the_category」などを使う。

しかし、カスタムポストで分類する際に使用したのはカテゴリーではなく「taxonomy」なので、表示や出力させたい場合はカスタムタクソノミーを使用する。

archive-works.php

      <?php /***** メインループ開始 *****/ ?>
      <?php if (have_posts()) : ?>
        <ul class="Works_list grid">
          <?php while (have_posts()) : the_post(); ?>
            <?php
            $taxonomy = 'genre';
            $terms = get_the_terms($post->ID, $taxonomy);
            foreach ($terms as $term) {
              $term_slug = $term->slug;
            }
            ?>
            <li class="item sort-<?php echo $term_slug; ?>">
              <figure class="item-content">
                <a class="Link" href="<?php the_permalink(); ?>">
                  <?php
                  if (has_post_thumbnail()) :
                    the_post_thumbnail('full', ['class' => 'Card_img']);
                  else :
                  ?>
                    <img src="<?php echo esc_url(get_stylesheet_directory_uri()); ?>/img/no-image.png" alt="<?php the_title(); ?>">
                  <?php endif; ?>
                </a>
              </figure>
            </li>
          <?php endwhile; ?>
        </ul>
      <?php endif; ?>
      <?php /***** メインループ終了 *****/ ?>

「archive-works.php」も「single-works.php」と同様に、カスタムタクソノミーを使用している。

カスタムタクソノミーで取得・出力できる情報

  • タームID(term_id):$term->term_id
  • ターム名(name):$term->name
  • タームスラッグ(slug):$term->slug
  • グループID(term_group):$term->term_group
  • タクソノミーID(term_taxonomy_id):$term->term_taxonomy_id
  • タクソノミー名(taxonomy):$term->taxonomy
  • タームの説明(description):$term->description
  • タームの親ID(parent):$term->parent
  • そのタームが付与されている投稿数(count):$term->count