Search code examples
phpwordpressblogscustom-wordpress-pagesposts

How to display only specific category label/name on page and hide other categories name?


I am trying to display only 1 category name and want to hide other categories name in post listing page.

add_filter('get_the_terms', 'hide_categories_terms', 10, 3);
function hide_categories_terms($terms, $post_id, $taxonomy){
$excludeIDs = array(1,322,320,321);

// get all the terms 
$exclude = array();
foreach ($excludeIDs as $id) {
    $exclude[] = get_term_by('id', $id, 'category');
}

// filter the categories
if (!is_admin()) {
    foreach($terms as $key => $term){
        if($term->taxonomy == "category"){
            foreach ($exclude as $exKey => $exTerm) {
                if($term->term_id == $exTerm->term_id) unset($terms[$key]);
            }
        }
    }
}

return $terms;

its hiding all the categories name but not showing the category name that I wanted to display it. Kindly help me out


Solution

  • You should be able to do this w/o have to get the exclude terms or the double loops:

    add_filter('get_the_terms', 'hide_categories_terms', 10, 3);
    function hide_categories_terms($terms, $post_id, $taxonomy){
        
        if ( ! is_admin() && is_single() ) {
            // filter for terms that are not in the exclude array
            $filtered_terms = array_filter($terms, function($term) {
                $excludeIDs = array(1, 322, 320, 321);
                return ! in_array($term->term_id, $excludeIDs);
            });
    
            // return filtered array of terms
            return $filtered_terms;
        }
    
        // return default terms JIC the above case is not met
        return $terms;
    }
    

    Another way you could write this to save some lines, if you are running PHP 7.4+:

    add_filter('get_the_terms', 'hide_categories_terms', 10, 3);
    function hide_categories_terms($terms, $post_id, $taxonomy){
        
        if ( ! is_admin() && is_single() ) {
            $excludeIDs = [1, 322, 320, 321];
            // filter for terms that are not in the exclude array
            $filtered_terms = array_filter($terms, fn($t) => ! in_array($t->term_id, $excludeIDs));
    
            // return filtered array of terms
            return $filtered_terms;
        }
    
        // return default terms JIC the above case is not met
        return $terms;
    }