PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

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

 July 08, 2022     blogs, custom-wordpress-pages, php, posts, wordpress     No comments   

Issue

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;
}


Answered By - mikerojas
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing