Exclude category from loop not working

I have this code in my index.php file. I have a different template for a static home page, this is the blog page. I’m trying to exclude all posts with the category “new” which is tag_id “13”

<?php query_posts($query_string . '&cat=-13'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><p class='lead'><?php the_title(); ?></p></a>

<p><?php the_excerpt(); ?> <a href="<?php the_permalink()?>">read in full</a></p>

<p class='muted'><small>Written by: <?php the_author_posts_link(); ?><br>               
            <?php the_time('F jS, Y') ?></small></p><hr>

<?php endwhile; ?>

Any ideas why this isnt working?

Related posts

Leave a Reply

3 comments

  1. Don’t use query_posts(). Use pre_get_posts instead:

    function wpse82745_filter_pre_get_posts( $query ) {
        // Only modify the main loop,
        // and only in the blog posts index
        if ( is_home() && $query->is_main_query() ) {
            $query->set( 'category__not_in', array( '13' ) );
        }
    }
    add_action( 'pre_get_post', 'wpse82745_filter_pre_get_posts' );
    

    This callback will exclude category 13 from the main loop in the blog posts index.

  2. The $query_string is probably not initialized or not declared as global variable. Try adding

    <?php global $query_string; ?>
    

    before your code

  3. I was running into the exact same mysterious issue, but struggling to solve it. I tried all of the suggestions in the comments here but nothing seemed to work.

    In the end, since the key was retaining the pagination (as this was on the main blog section of the site and I wanted to exclude ‘Other News’), I tried this:

    //  Exclude the Other News category
    
    $otherNews = get_category_by_slug('other-news'); 
    $excludeID = $otherNews->term_id;
    
    //query_posts($query_string . '&cat=-' . $excludeID);   <-- Doesn't work for some reason
    
    $args = array('cat' => '-' . $excludeID, 'paged' => $paged );
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    query_posts($args);
    

    …and this seemed to work perfectly.