0

I am trying to get a list of all categories that the current post is not in. I made it this far...

$categories = get_the_category( $post_id );
$nocats = get_terms('category', array('exclude' => $categories) );
foreach ( $nocats as $nocat ) {echo $nocat->name;echo ","; }

...but it's not working. I guess it has to do with imploding the $categories array, but the thing threw an error when I tried this...

$categories = get_the_category( $post_id );
$excats = implode(',', $categories);
$nocats = get_terms('category', array('exclude' => $excats) );
foreach ( $nocats as $nocat ) {echo $nocat->name;echo ","; }

... so now I'm stuck. What am I doing wrong?

2

Ok. So, the first bit of code is more correct but it has issues nonetheless. Piece by piece...

$categories = get_the_category( $post_id );

$post_id is not set in the code you posted. I assume that value is set earlier in the page somewhere, else that is your first problem.

$nocats = get_terms('category', array('exclude' => $categories) );

The exclude argument will accept an array of term IDs, but that is not what get_the_category() returns. It returns an array of objects. You cannot use that as is. (This, by the way, is the same reason you are having trouble with $excats = implode(',', $categories);. You are trying to convert objects into strings). You need to extract the IDs:

$categories = wp_list_pluck($categories,'term_id');

Then:

$nocats = get_terms('category', array('exclude' => $categories) );

There is one further step: get_terms() by default will only return categories that have posts assigned to them. If you truly want to show all categories you need to add 'hide_empty' => false to your argument list:

$nocats = get_terms(
  'category', 
  array(
    'exclude' => $categories,
    'hide_empty' => false
  ) 
);

Now your code should work:

$categories = get_the_category( $post->ID );
// var_dump($categories);
$categories = wp_list_pluck($categories,'term_id');
// var_dump($categories);
$nocats = get_terms(
  'category', 
  array(
    'exclude' => $categories,
    'hide_empty' => false
  ) 
);
// var_dump($nocats);
foreach ( $nocats as $nocat ) {
  echo $nocat->name;
  echo ","; 
}

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.