0

I have a custom page template that uses the wordpress loop to display all my posts like usual:

<?php if (have_posts()) : while (have_posts()) : the_post();

There is a category that I don't want to display on this page. The id of this category is 3.

So I though I could use something like this:

<?php if (have_posts()) : while (have_posts()) : the_post();
          if ( in_category('3') ) continue;
               the_content();
          endwhile;
      endif; 
?>

But the posts with this category ID are still displaying.

I've also tried adding this to functions.php:

function exclude_category($query) {
    if (isset($query)) {
        $query->set('cat', '-3');
    }
    return $query;
}
add_filter('pre_get_posts', 'exclude_category');

This works, but it is global to every page on the site (obviously), which is what I don't want. I just want category ID removed from this single page template.

Is it possible to do this?

2
  • What do you mean custom page template? pre_get_posts doesn't work on page templates. Exactly what template? Commented Jan 14, 2015 at 19:08
  • its a custom template called location-template.php. I used "pre_get_posts" in the functions.php file. This works to exclude the category from anywhere the wordpress loop is being used. I just want to exclude this category from being displayed in location-template.php Commented Jan 14, 2015 at 19:13

1 Answer 1

0

Did you try:

function exclude_category($query) {
    if ( is_page('slug-of-page') && isset($query) ) {
        $query->set('cat', '-3');
    }
    return $query;
}
add_filter('pre_get_posts', 'exclude_category');
6
  • Yes, I tried that, and the posts in that category are still showing up on the page with the slug that I give it. also tried is_page_template('location-template.php'), but I'm not sure these will work in functions.php because functions.php is loaded before the page loads. Commented Jan 14, 2015 at 19:24
  • Try it without the quotes: if ( in_category(3) ) continue; Maybe WP is parsing 3 as a string, not an integer, so it's looking for a Category called "3", not an Category with an ID of 3.
    – darrinb
    Commented Jan 14, 2015 at 19:26
  • Yeah that still didn't work :( Commented Jan 14, 2015 at 19:29
  • This is technically the blog template. The posts in that category are displaying on /blog/page/9/. --- I wonder if /blog/page/9/ is a different template? Commented Jan 14, 2015 at 19:33
  • Take that back, removing the quotes seemed to fix it! thanks buddy! :) Commented Jan 14, 2015 at 19:39

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.