カスタム投稿タイプでカテゴリとタグを使う

内容が古いのでアップデート

Custom Post Type UI
を使う。
カスタム投稿タイプ使用する際に。今までfunctions.php直接編集してたけど、こっちの方が楽。

おしまい。

以下は古い内容なので、参考にならない。
というか、いけない。

WordPressの投稿にあるようなカテゴリやタグを、カスタム投稿タイプでも使いたい。

function.phpに追加して使用していたのだけど、カテゴリだけではなくタグも利用したくなった。
register_post_typeのsupportsに追加すれば良いのかと思ったけど、違ったのでメモ。

カテゴリもタグも、ようはカスタムタクソノミーを使うのだけど。

カテゴリのような入力欄を記事投稿画面に欲しい場合は、register_taxonomyのhierarchicalをtrueに。
タグのような入力欄を記事投稿画面に欲しい場合は、register_taxonomyのhierarchicalをfalseに。

この二つは併用できる。

具体的にはこんな感じ。
追加する投稿タイプを仮に「products」とした場合。

add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'products', /* post-type */
    array(
      'labels' => array(
        'name' => __( '製品' ),
        'singular_name' => __( '製品' )
      ),
      'public' => true,
      'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields' ,'comments' ),
      'menu_position' =>5,
      'has_archive' => true
    )
  );
  
//カスタムタクソノミー、カテゴリタイプ
  register_taxonomy(
    'products-cat', 
    'products', 
    array(
      'hierarchical' => true, 
      'update_count_callback' => '_update_post_term_count',
      'label' => '製品のカテゴリー',
      'singular_label' => '製品のカテゴリー',
      'public' => true,
      'show_ui' => true
    )
  );
  
//カスタムタクソノミー、タグタイプ
  register_taxonomy(
    'products-tag', 
    'products', 
    array(
      'hierarchical' => false, 
      'update_count_callback' => '_update_post_term_count',
      'label' => '製品のタグ',
      'singular_label' => '製品のタグ',
      'public' => true,
      'show_ui' => true
    )
  );

}

こんな感じで記事の入力欄にカテゴリとタグの入力欄が表示されるようになる。

シェアする

  • このエントリーをはてなブックマークに追加

フォローする