Search code examples
phpwordpresscategoriescustom-post-type

Disable the Category option for Custom Post Type in Wordpress


I'm working on a site where the user can add videos to a slider using a custom post type. In reality, there are three different sliders and the videos that go inside each are determined by the category they're assigned. Here's the code that registers the cpt:

public function videos() {
    register_post_type( 'videos',
            [
            'labels'       => [
              'name'          => 'Videos',
              'singular_name' => 'Videos'
              ],
            'public'       => true,
            'show_in_rest' => true,
            'taxonomies'   => [ 'category' ],
            'rewrite'      => [ 'slug' => 'videos' ],
            'supports'     => [ 'title', 'custom-fields', 'editor', 'excerpt', 'thumbnail' ],
            'menu_icon'    => 'dashicons-format-video'
        ]
    );
  }
}


I've added three different categories through WP Admin and I want to prevent users from being able to use or create any other categories other than the ones I've created, so in order to to that, I'd like the "Categories" tab of the CPT menu inside the Admin bar to not be there, and I want the same for the '+ Add New Category' link in the custom post metabox. Bottom line, the user should have no business handling categories, other than assigning already existing ones to new posts.

This seemed like a pretty simple and common fix so I'm surprised as I wasn't able to find a working solution on so far. This is very close to what I'm looking for, but as I haven't added the register_taxonomy_for_object_type( 'category', 'custom_type' ); line, I don't have anything to remove. I'm very confused by all this and any help would be appreciated.


Solution

  • 'taxonomies' => [ 'category' ] is your way of calling register_taxonomy_for_object_type( 'category', 'custom_type' ); but by removing that, you remove the taxonomy from the post type, not just the menu.

    I'd suggest you register a custom taxonomy for your videos and assign admin capabilities to it.

    Registering taxonomies: https://developer.wordpress.org/reference/functions/register_taxonomy/

    The capabilities option will allow you to only allow admins to alter them, so your capabilties would look something like this.

    'capabilities' => array(
        'manage_terms'          => 'update_core',
        'edit_terms'            => 'update_core',
        'delete_terms'          => 'update_core',
    ),
    

    In the end you will have a custom post type which moderators/editors can manage and a custom taxonomy attached to that post type which only admins can alter but mods/editors can assign.