0

this should be simple, but it seems it is not. I simply want to not list some of the current post's categories, just exclude them from the list of categories the current post belongs to

I use this for listing the current post's categories (but I am open to using whatever would work):

<?php the_category( ', ' ); ?>

and I tried this code on functions.php

    function my_category_filter($cats){
   //exclude these from displaying
   $exclude = array(4,);
   $Catds = array();
   foreach ($cats as$cat){
      if (!in_array($cat,$exclude)){$Catsa[] = $cat;}
   }
   return $Catsa;
}

add_filter('the_category','my_category_filter');

but no category will show if I use it. Maybe you can guide me into solving this?

thanks!

1
  • 1
    I posted an answer, but note that in your code, there's a typo - $Catds should be $Catsa ..
    – Sally CJ
    Apr 1 at 2:39

1 Answer 1

1

The problem here is you're not using the proper hook because the_category is actually for modifying the HTML of the category list, and the 1st parameter for the hook is actually a string and not an array.

So the hook that you should have used is the_category_list where the 1st parameter is an array of terms/categories, but note that each item is an object (a WP_Term instance) and not a category ID.

And with your current code, you just need to make 2 changes:

  1. Change the add_filter() to using the_category_list instead:

    add_filter('the_category_list','my_category_filter');
    
  2. In your foreach, change the if to using $cat->term_id instead:

    if (!in_array($cat->term_id,$exclude))
    

So now your code should work correctly, but it also would work on any "current post", e.g. the one in the current loop, so you might need to add a condition to your function so that it only applies to specific posts.

Or you could actually manually generate the categories list/HTML, e.g. using get_the_category():

// ID's of the categories you want to be excluded.
$exclude = array( 4 );

// The categories list.
$cat_list = array();

foreach ( get_the_category() as $cat ) {
    if ( ! in_array( $cat->term_id, $exclude ) ) {
        $cat_list[] = '<a href="' . esc_url( get_category_link( $cat->term_id ) ) .
            '">' . $cat->name . '</a>';
    }
}

// Display a simple comma-separated list of links.
echo implode( ', ', $cat_list );

Then in your template, use the above code instead of the the_category(). That way, you can avoid messing with the categories list for other "current post".

1
  • 1
    I didn't manage to make the first code to work, but your second code works perfectly. thank you so much!
    – vyperlook
    Apr 1 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.