Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPBカップ
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

WordPressでカスタム投稿タイプにカテゴリーを追加する方法

編集メモ: WPBeginner のパートナーリンクから手数料を得ています。手数料は編集者の意見や評価に影響を与えません。編集プロセスについて詳しく知る。

カスタム投稿タイプにカテゴリーを簡単に追加する方法をお探しですか?

カテゴリーはWordPressにビルトインされているタクソノミーの一つですが、初期設定では投稿にしか表示されません。

この投稿では、WordPressのカスタム投稿タイプにカテゴリーを追加する方法を紹介する。

Adding categories to custom post types in WordPress

カスタム投稿タイプにカテゴリーを追加する必要がある場合は?

WordPressでは、プラグイン開発者やサイトオーナーが独自のコンテンツタイプを作成することができます。投稿やページと同様に、これらのカスタム投稿タイプもカテゴリーやタグのような独自のタクソノミーを持つことができます。

例えば、映画のレビューを公開するのであれば、’Movies’のカスタム投稿タイプを作成するとよいでしょう。

また、映画を適切なトピックに整理する必要があるかもしれませんが、そのためにはカスタマイノミーが必要です。ジャンルというタクソノミーを作成することができます。

しかし、ブログ投稿に使っているカテゴリーをムービー投稿タイプにも使いたいとしたらどうだろう?

このとき、カスタム投稿タイプのカテゴリーを有効化する必要がある。これにより、ブログ投稿とカスタム投稿タイプの両方に同じカテゴリーを使用できるようになります。

ということで、WordPressのカスタム投稿タイプにカテゴリーを簡単に追加する方法を見ていきましょう。

プラグインでカスタム投稿タイプにカテゴリーを追加する

初心者の方は、カスタム投稿タイプを作成するためにCustom Post Type UIプラグインを使用することをお勧めします。

カスタム投稿タイプUIプラグインを使用すると、カテゴリを含む任意のビルトインまたはカスタムのタクソノミーにカスタム投稿タイプを関連付けるオプションがあります。

まず、カスタム投稿タイプUIプラグインをインストールして有効化する必要があります。詳しくは、WordPressプラグインのインストール方法のステップバイステップガイドをご覧ください。

インストーラをインストールしたら、CPT UI ” Add/Edit Post Typesにアクセスして、新規カスタム投稿タイプを作成するか、プラグインで作成した既存のカスタム投稿タイプを編集する必要があります。

Editing post types with CPT UI plugin

設定オプションがある一番下までスクロールします。そこから、Taxnomiesエリアが表示されます。

カテゴリーの次のボックスにチェックを入れ、カスタム投稿タイプを保存する必要があります。

Turn on categories for a Custom Post Type in WordPress

投稿タイプを保存」ボタンをクリックして、設定を保存することをお忘れなく。

これで、特定の投稿タイプの下にあるコンテンツを編集できるようになり、WordPressブロックエディターの右カラムにカテゴリーを選択するオプションが表示されます。

Category added to a custom post type

コードを使ってカスタム投稿タイプにカテゴリーを手動で追加する

テーマのfunctions.phpファイル、サイト固有のプラグイン、またはコードスニペットプラグインにコードを追加してカスタム投稿タイプを作成した場合は、対応するタクソノミーとしてカテゴリーを追加するためにコードを修正する必要があります。

必要なのは、カスタム投稿タイプの引数に次の行を追加することだけだ。

'taxonomies'  => array( 'category' ),

カスタム投稿タイプの既存のコードにすでにこの行があり、その中に他のカスタムタクソノミーが含まれている可能性があります。もしそうであれば、次のようにカンマの後にカテゴリーを追加するだけです:

'taxonomies'          => array('topics', 'category' ),

以下は、ビルトインカテゴリーをサポートした’Movies’というカスタム投稿タイプを作成したコード例です。

function custom_post_type() {
 
// Set UI labels for Custom Post Type
    $labels = array(
        'name'                => _x( 'Movies', 'Post Type General Name', 'twentythirteen' ),
        'singular_name'       => _x( 'Movie', 'Post Type Singular Name', 'twentythirteen' ),
        'menu_name'           => __( 'Movies', 'twentythirteen' ),
        'parent_item_colon'   => __( 'Parent Movie', 'twentythirteen' ),
        'all_items'           => __( 'All Movies', 'twentythirteen' ),
        'view_item'           => __( 'View Movie', 'twentythirteen' ),
        'add_new_item'        => __( 'Add New Movie', 'twentythirteen' ),
        'add_new'             => __( 'Add New', 'twentythirteen' ),
        'edit_item'           => __( 'Edit Movie', 'twentythirteen' ),
        'update_item'         => __( 'Update Movie', 'twentythirteen' ),
        'search_items'        => __( 'Search Movie', 'twentythirteen' ),
        'not_found'           => __( 'Not Found', 'twentythirteen' ),
        'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),
    );
     
// Set other options for Custom Post Type
     
    $args = array(
        'label'               => __( 'movies', 'twentythirteen' ),
        'description'         => __( 'Movie news and reviews', 'twentythirteen' ),
        'labels'              => $labels,
        'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 5,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
        'show_in_rest'        => true,
         
        // This is where we add taxonomies to our CPT
        'taxonomies'          => array( 'category' ),
    );
     
    // Registering your Custom Post Type
    register_post_type( 'movies', $args );
 
}
 
/* Hook into the 'init' action so that the function
* Containing our post type registration is not 
* unnecessarily executed. 
*/
 
add_action( 'init', 'custom_post_type', 0 );

カテゴリーページでの複数投稿タイプの表示

初期設定では、WordPressサイトのカテゴリーページはデフォルトの「投稿」投稿タイプのみを表示します。

Missing post type

カスタム投稿タイプをデフォルト投稿と同じカテゴリーページに表示するには、テーマのfunctions.phpファイルまたはコードスニペットプラグインにこのコードを追加する必要があります:

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
  if( is_category() ) {
    $post_type = get_query_var('post_type');
    if($post_type)
        $post_type = $post_type;
    else
        $post_type = array('nav_menu_item', 'post', 'movies'); // don't forget nav_menu_item to allow menus to work!
    $query->set('post_type',$post_type);
    return $query;
    }
}

注:「movies」を自分のカスタム投稿タイプの名前に置き換えることをお忘れなく。

私たちは、市場で最高のコードスニペットプラグインであるWPCodeを使用して、このコードを追加することをお勧めします。WPCodeを使用すると、テーマのfunctions.phpファイルを編集することなく、WordPressでカスタムコードを安全かつ簡単に追加することができます。

WPCode

開始するには、無料のWPCodeプラグインをインストールし、有効化する必要があります。ヘルプが必要な場合は、WordPressプラグインのインストール方法のチュートリアルを参照してください。

プラグインを有効化したら、WordPressダッシュボードからCode Snippets ” Add Snippetに移動します。

スニペット追加ページから、「カスタムコードを追加(新規スニペット)」オプションにマウスオーバーし、「スニペットを使用」ボタンをクリックします。

Add a new custom code snippet in WPCode

次に、ページの一番上にスニペットのタイトルを追加します。これは参照用で、何のコードかを覚えておくのに役立つものであれば何でも構いません。

次に、上記のコードを「コードプレビュー」ボックスに貼り付け、右側のドロップダウンメニューからコードタイプとして「PHPスニペット」を選択します。

Paste code into the Code Preview box and choose the code type

その後、ページ上部のスイッチを「非有効化」から「有効化」に切り替え、「スニペットを保存」ボタンをクリックするだけです。

Activate and save your custom code snippet

カテゴリーアーカイブページにアクセスすると、カスタム投稿タイプのエントリーが表示されるようになりました。

Post type displayed on categories archive page

カスタム投稿タイプにも同じ方法でタグを追加することができます。さらに詳しく知りたい方は、カテゴリーとタグに関するガイドをご覧ください。

WordPressのカテゴリーに関するエキスパートガイド

WordPressのカテゴリーの使い方についてさらに詳しく知りたいですか?以下のチュートリアルをご覧ください:

WordPressのカスタム投稿タイプにカテゴリーを追加する方法について、この投稿がお役に立てれば幸いです。あなたのサイトを成長させるWordPressプラグインやブログのトラフィックを増やすためのヒントもご覧ください。

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

情報開示 私たちのコンテンツは読者支援型です。これは、あなたが私たちのリンクの一部をクリックした場合、私たちはコミッションを得ることができることを意味します。 WPBeginnerの資金源 をご覧ください。3$編集プロセスをご覧ください。

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

究極のWordPressツールキット

ツールキットへの無料アクセス - すべてのプロフェッショナルが持つべきWordPress関連製品とリソースのコレクション!

Reader Interactions

40件のコメント返信を残す

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Chandu Mullangi says

    Hi tanks for this article

    To Displaying Multiple Post Types on Category Page code is working well.

    I want to display multiple post types on Tags page, Can you please share that code.

    • WPBeginner Support says

      To have tags added to your custom post types you would add ‘post_tag’ to your taxonomy array so it would look like:

      ‘taxonomies’ => array( ‘category’, ‘post_tag’ ),

      管理者

  3. Muhamad Shahzad says

    How can we separate the category lists custom post type from the blog post categories. i added above code and it works. But the issue is categories of this custom post type and blog posts are mixed. they should be separated.

    • WPBeginner Support says

      The goal of this tutorial is to have them mix, for what you are looking for it may be best to use a different category for the custom post types for them to not appear in your category archive pages.

      管理者

  4. Poulomi Basu says

    Hello,
    I used this code and it worked perfectly! The CPT shows in the post category that I chose for it.
    But it doesn’t show in my blog archive. Like the default archive, which shows all posts.
    How can I show it there as well?

    Thanks a lot!

  5. Connie says

    Please tell me how to add a CPT-category to a menu?

    I have the CPT “article” with category “car” and “truck”

    I want to have a custom menu with these entries:

    All – cars – trucks

    I search and search and don’t find it. I see the categories in the menu-administration and I can add them to the menue, but the result of these links = blank pages
    I suppose that the listed categories are meant as post-categpories and not as cpt-categpories…

    Do you have a hint for me?

    Connie

    • WPBeginner Support says

      You may want to check your screen options in the menu area to see if the custom post type is an option there for you to add that is unchecked currently

      管理者

  6. Vico says

    I’ve created a post type called products and use core wp categories,
    My product url structure is mysite.com/product/skf bearing 12
    My category pages show mysite.com/category/bearings
    Why product url doesn’t display the Category inside the Url? Like this
    mysite.com/bearings/skf bearing 12
    My custom post permalink is %category%%post%
    I saved the permalink but still showing the same structure

  7. dharamjeet says

    hey! my default posts category list shows in custom post type category list

    please help me to correct it

    • WPBeginner Support says

      Hi Moises,

      This string is used for translation. If your theme supports translation, then you need to replace it with your theme’s text domain. If you are unsure about what to use here, then ask your theme support. You can also paste it as is and those strings will be ignored.

      管理者

  8. Brian says

    FYI, this will break your bulk edit in the admin. I added this to a bunch of post types and when I go to bulk edit, the post_type part of the query becomes “Array” instead of the post type its trying to edit in the admin.

    To get around this you just need to add this before if( is_category() ):

    `if ( is_admin() ) return;`

  9. rose says

    Hi, I need some help.
    I have 2 CPT and I don’t want them to have a shared taxonomy.
    Like
    CPT 1
    – Taxonomy (Types)
    – Type A
    – Type B
    CPT 2
    – Taxonomy (Types)
    – Type c
    – Type D
    Note: I dont want to show here the types A&B from CPT 1
    Thank you

  10. Arun Sathiya says

    The displaying CPT in category pages code works like a charm, thank you! But, there is something that you should note though. The latest post / CPT post tagged with a category name does not show up on that category page immediately. It shows up only on the second similar action – only when another post / CPT post is added to the same category, the first post appears on that category page. is there a fix to this?

  11. Sonjoe says

    I am using CPT UI. I created custom post type “jobs” and allowed categories. But this same categories is also on Posts. They using the same categories. It is possible, that my custom post type “jobs” will have own categories and classic posts will have own categories? Thanks

    • Rizky says

      Same question. Do we need to run a custom query if we want to create a category archive of that custom post type?

  12. fathur says

    how do you deal with Recent Posts sidebar widget that also list the menu item?

    $post_type = array(‘nav_menu_item’, ‘post’, ‘movies’);

  13. vivek says

    Thanks for the great tutorial here. :)

    Can you please tell me how can i show custom posts by category on separate page.

    Default category page is working properly, it displays the posts. but when I tried to display posts under the same category in a different page, it returns empty array. Pleas help

  14. Matthew Wright says

    Thank you! This is awesome. It solved simply a problem that I’ve been working on with much more convoluted solutions (that didn’t work).

    One question though, I’ve never added the taxonomy declaration when creating custom taxonomies for my CPTs and the taxonomies have always worked. I added just the ‘category’ to see what would happen and it worked beautifully, added post categories to my CPT with no ill effect on the existing custom taxonomies.

    Is it best practice though to put custom tax in the CPT arguments?

    Thanks again for sharing :)

  15. Daisy says

    Custom code for adding category and sub categorues in custom post type.If i choose $post_type = array(‘nav_menu_item’, ‘post’, ‘myPostType’); code for displaying my categories it only display that category only but if i reuse the same function for another category it won’t work.please give any idea

  16. Chris Najman says

    Hello. I successfully created a custom post type (Artwork) in functions.php. Then I created a custom taxonomy (‘hierarchical’ => true) which means I can add custom categories when I create a new Artwork post.

    I was wondering if, within the same custom taxonomy function, I could pre-define the categories for the Artwork post.

    What I want are only two categories to be selectable by the user : 1) Painting, 2) Sculpture. I don’t want the user to be able to add any more categories. Ideally, the user would be ‘forced’ to choose one or the other category, i.e. the post wouldn’t be publishable unless a category had been chosen.

    Is this possible?

  17. Mau Ferrusca says

    I am adding more then one categories to several custom post types.

    How can you add more than one in the line:

    $post_type = array(‘nav_menu_item’, ‘post’, ‘myPostType’);

    ?

    Thanks!

    • Mau Ferrusca says

      Already solved my problem.

      Perhaps instinctively, I started listing my custom post types as an array, but turns out that all I needed to do was to list them inside the $post_type object, separated with commas.

      Thanks!

  18. Eren says

    Hi, i have a question. I’m using a plugin as a post type and it has its own category area. I want to use my wordpress’s core categories in this plugin but couldnt able to do it so far. I used the plugin above and after that it creates 2 categories area under the plugin and when i want to show the posts under that post type with categories, it shows nothing as the plugin’s own category list is empty. I tried lots of things including manipulating the code of the plugin yet none solved my issue. Is there a way you can suggest?

  19. David says

    Has this article been updated recently to work with the current version of WP? I noticed the plugin used hasn’t been updated in over 2 years, which makes me a little hesitant to use it.

  20. Piyush says

    Thanks for the great tutorial. can you please tell me how can i show custom posts by category on separate page. Lets say i have CPT “talent” and a category “art”. I have two different posts one is created under CPT “talents” and other is general post created under “posts”. Both posts are assigned to “art” category(this is common for both CPT and general posts). Now i know that for the general posts you can view the category page as example.com/category/art/. For CPT category page i guess the url should be example.com/talent/art/ but it is giving me 404 error.

  21. Robert says

    Well done thanks!
    I have a couple of troubles:
    – in “Categories” widget appear the Categories of Custom Post Types but on clic it returns a “nothing found” message.
    – in “Recent Posts” widget don’t appear Custom Post Type Posts.
    There is a way to fix it?

  22. Hemang Rindani says

    Interesting article. WordPress is a powerful enterprise web content management service that allows a company to have efficient websites that suits their business requirements. It’s easy to use and effortless tools makes the development look easier. From responsive design to security and expand-ability, WordPress CMS has it all in it however, searching the right tools for a website is important.
    Adding category to custom post type sometimes becomes a necessity for differentiating one post from other where the methods mentioned in the article will be useful. Using plugin will be an easy method where even a non-technical person will be able to implement this, however with this article, I don’t feel that using code to add this feature by a non-technical person will be difficult.
    Thanks for sharing.

返信を残す

コメントありがとうございます。すべてのコメントは私たちのコメントポリシーに従ってモデレートされ、あなたのメールアドレスが公開されることはありませんのでご留意ください。名前欄にキーワードを使用しないでください。個人的で有意義な会話をしましょう。