I am trying to exclude categories from my blog page. I have the code all set up and according to the codex, this should work

 $string = '-' . implode( ',-', explode( ' ', $data['exclude_categories'] ) );

The above line will print this to the screen upon testing


Those are the two test categories that I am trying to remove from the blog page. Then I start my query like so

 <?php query_posts($query_string .  '&cat=' . $string);?>
    <?php if (have_posts()) : ?>
        <?php while (have_posts()) : the_post(); ?> 
 my other code stuff here

when I test the blog page, all the posts show up. I can't figure out what is wrong.

1 Answer 1


cat accepts category IDs, not slugs or names. a better method here is to use the pre_get_posts action, the Codex page has an example that does exactly what you're trying to do.

  • that method doesn't work for me either. In the example, they are using ID's also. The function uses is_home(), my blog isn't on the homepage. I tried is_page but that gave me undefined index errors. I also tried category_name =- homepage but that gave me weird results. It cut out the wrong category
    – Jamie
    Commented Sep 17, 2012 at 0:55
  • if your blog is assigned to a page under reading settings, then it is the home page, see conditional tags for more info. you can't exclude using category names, you have to use IDs.
    – Milo
    Commented Sep 17, 2012 at 1:06
  • Ok, thanks Milo. I have used my method above in the past but I realized after your comments that the framework returned the ID instead of the category slug.
    – Jamie
    Commented Sep 17, 2012 at 2:19
  • I have been been looking over my code above. So I am trying to get the category id by using the get_category_by_slug() but I am getting nothing when I echo out for a test. when I tried using a foreach loop, I got an invalid argument passed to implode $cat = explode( ', ', $data['exclude_categories'] ) ; foreach ($cat as $categories){ $string = get_category_by_slug( implode(',',$categories)); echo $string; }
    – Jamie
    Commented Sep 17, 2012 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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