Hide/Show only specific categories in wp-admin new-post.php

Can anyone give me a function or an idea of the method I would need to use to hide categories from the selection box in wp-admin?

I have a custom post type and I would like my authors to be able to choose ONLY between 5 of those categories while they are editing their posts. I would like this to only be the case with the custom post type and NOT for regular posts.

Related posts

Leave a Reply

1 comment

  1. Something like this should do it. Replace wpse_77670_getPermittedCategories() with however you select the array of permitted categories, and 'your_custom_category' with whatever your custom taxonomy is for your custom post type.

    /**
    * filter terms checklist args to restrict which categories a user can specify
    * @param array $args arguments for function get_terms()
    * @param array $taxonomies taxonomies to search
    * @return array
    */
    function wpse_77670_filterGetTermArgs($args, $taxonomies) {
        // check whether we're currently filtering selected taxonomy
        if (implode('', $taxonomies) == 'your_custom_category') {
            $cats = wpse_77670_getPermittedCategories();    // as an array
    
            if (empty($cats))
                $args['include'] = array(99999999);     // no available categories
            else
                $args['include'] = $cats;
        }
    
        return $args;
    }
    
    if (is_admin()) {
        add_filter('get_terms_args', 'wpse_77670_filterGetTermArgs', 10, 2);
    }
    

    Edit, to work with regular ‘category’ taxonomy on custom post type:

    function wpse_77670_filterGetTermArgs($args, $taxonomies) {
        global $typenow;
    
        if ($typenow == 'tsv_userpost') {
            // check whether we're currently filtering selected taxonomy
            if (implode('', $taxonomies) == 'category') {
                $cats = array(89,90,91,92,93,94); // as an array
    
                if (empty($cats))
                    $args['include'] = array(99999999); // no available categories
                else
                    $args['include'] = $cats;
            }
        }
    
        return $args;
    }
    
    if (is_admin()) {
        add_filter('get_terms_args', 'wpse_77670_filterGetTermArgs', 10, 2);
    }