LoginSignup
0
1

カテゴリ別施工事例追加(カスタム投稿タイプ)

Last updated at Posted at 2024-02-22

前提

通常の投稿タイプをお知らせで使用しており、カスタム投稿タイプで施工事例を追加したい

流れ

  1. functions.phpに施工事例のカスタム投稿タイプを管理画面に表示するように設定。カスタム投稿タイプにカテゴリとタグが表示される記述を書く。


/* ---------- カスタム投稿タイプを追加 ---------- */
add_action( 'init', 'create_post_type' );

function create_post_type() {

  register_post_type(
    'works',
    array(
      'label' => '施工事例',
      'public' => true,
      'has_archive' => true,
      'show_in_rest' => true,
      'menu_position' => 5,
      'supports' => array(
        'title',
        'editor',
        'thumbnail',
        'revisions',
      ),
    )
  );

  register_taxonomy(
    'workscat',
    'works',
    array(
      'label' => 'カテゴリー',
      'hierarchical' => true,
      'public' => true,
      'show_in_rest' => true,
    )
  );

  register_taxonomy(
    'workstag',
    'works',
    array(
      'label' => 'タグ',
      'hierarchical' => false,
      'public' => true,
      'show_in_rest' => true,
      'update_count_callback' => '_update_post_term_count',
    )
  );

}
  1. Custom Post Type Permalinksのプラグインを入れて、カスタム投稿タイプのURL構造を決定。末尾を/%post_id%にする。

  2. archive-works.phpとsingle-works.phpという名前のファイルを作り、archive-works.phpを固定ページのテンプレートにする。

  3. 管理画面から施工事例ページをつくり、テンプレートを適用。

  4. archive-works.phpの中とsingle-works.phpの中に呼び出したい内容を書く。※この時、カスタム投稿タイプのループのみを取得するため、Queryにカスタム投稿タイプ名「works」を入れる。いつものお知らせに使用している、
<?php
      if ($query->have_posts()) :
      while ($query->have_posts()) : $query->the_post(); ?>

の部分を下記に変更するだけ

<?php
  $args = [
    'post_type' => 'works', // カスタム投稿名
  ];
  $my_query = new WP_Query($args); ?>
 
<?php if ($my_query->have_posts()): // 投稿がある場合 ?>               
           <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>

カテゴリを表示したいときは、

<?php
  // カテゴリーのデータを取得
  $cat = get_the_category();
  $cat = $cat[0];
?>

上記をループ前に書き、出力表示したいところに以下を書く

<?php
        if ($terms = get_the_terms($post->ID, 'workscat')) {
               foreach ( $terms as $term ) {
               echo ('<span>') ;
               echo esc_html($term->name)  ;
               echo ('</span>') ;
            }
        }
    ?> 
0
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
0
1