Skip to content
Advertisement

Excluding categories in WordPress with “list_terms_exclusions” not showing results

I am using the filter list_terms_exclusions to exclude categories in the WordPress admin panel for users with a certain role. The following code is what I have put together:

add_filter( 'list_terms_exclusions', 'nsf_exclude_cats', 20 );
function nsf_exclude_cats( $exclusions ) {
    global $pagenow;
    global $nsf_exclude; // array from another function, with all the cat_ID's to be excluded

    if (current_user_can( 'krets_editor' ) && is_admin() ) {
        $exclusions .= ' AND t.term_id NOT IN (';
        foreach($nsf_exclude as $exclude) {
            $exclusions .= $exclude.',';
        }
        $exclusions = substr($exclusions, 0, -1); // Removing the last comma
        $exclusions .= ')';
    }
return $exclusions;
}

This is “almost working”. When I go to “Categories” in WordPress admin, I see that the total counted categories is correct (there is over 200 categories, but 8 should be returned for this user). But the table is empty (!), no categories are shown!

enter image description here

But if I press the “Name” column header for example, to sort the results so the URL is changed with the orderby parameter, it is working as intended and the table is filled. What am I missing here that is the reason for the results not showing in the default view?

enter image description here

Advertisement

Answer

As I am checking your code we found a very small issue with $nsf_exclude

$nsf_exclude = empty (no category id exist), that’s why your function restricts all categories. but if you click on sorting then cat id set in your global variable that’s why it’s visible by click on sorting.

====== Debugging ======

  1. Proper set cat id $nsf_exclude

  2. print $nsf_exclude. eg print_r($nsf_exclude);

  3. If page onload/refresh return/print cat ids then it will work

  4. Other way set cat id manuall and verify

    eg. global $nsf_exclude;

    $nsf_exclude = array(115,136);

=========== Working Function ===================

add_filter( 'list_terms_exclusions', 'nsf_exclude_cats', 20 );
function nsf_exclude_cats( $exclusions ) {
    global $pagenow;
    global $nsf_exclude; // array from another function, with all the cat_ID's to be excluded
    $nsf_exclude = array(115,136); 
    if (current_user_can( 'administrator' ) && is_admin() ) {
        if(!empty($nsf_exclude)){
            $exclusions .= ' AND t.term_id NOT IN (';
            foreach($nsf_exclude as $exclude) {
                $exclusions .= $exclude.',';
            }
            $exclusions = substr($exclusions, 0, -1); // Removing the last comma
            $exclusions .= ')';
        }
    }
    return $exclusions;
}

Note:

After test remove or comment $nsf_exclude = array(115,136);

Where 115,136 is the product category ids (you can replace with own cat ids)

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement