WordPress.org

Ready to get started?Download WordPress

Forums

Excluding multiple categories from index (2 posts)

  1. Phoat
    Member
    Posted 7 years ago #

    After racking my brain over this for about a month, today I suddenly had an epiphany and thought I'd share.

    Using the following code taken from the WordPress codex, you can exclude any one category (in this example category with index 11) from the index listing.


    <?php $temp_query = $wp_query; ?>
    <?php query_posts('cat=-11&showposts=1'); ?>
    <?php while (have_posts()) : the_post(); ?>
    <div class="post">
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <small><?php the_time('F jS, Y'); ?></small>
    <div class="entry">
    <?php the_content(); ?>
    </div>
    <p class="postmetadata">Posted in <?php the_category(', '); ?>
    <?php endwhile; ?>
    <?php $wp_query = $temp_query; ?>

    But what if you want to exclude more than one category? I tried this simple solution and surprisingly, it worked.

    All you need to do is group all the categories that you want to exclude into another parent category and then only exclude the parent.

    So for example, let's say I have categories Projects, Photos, Portfolio, and Features that I want to exclude. I would make these child categories of category Hidden and then only exclude that parent category. Then in the code above I assign the index of category Hidden to the cat variable as so...

    <?php query_posts('cat=-11&showposts=1'); ?>

    The showposts variable allows you to control the number of posts that will be shown on the index. I have 1 cause I only wanted to show 1 post on the index.

    When creating your posts, you only need to assign the child category to the post (no need to assign category Hidden) and it will hide those children categories from the index.

    Good thing with the code above is that you can include it in your index.php more than once so you can have multiple loops on your index page. I did this on my blog to seperate the latest post from all the other posts allowing me to style it differently (and the reason why the showposts variable is equal to 1).

    So there you have it. I hope this works for everyone and isn't just a freak accident that just happened to work on my configuration.

    I welcome comments and thought.

  2. tukanuk
    Member
    Posted 7 years ago #

    Thanks so much for sharing this tip. I've been trying to find a clean way to do this for about two months (I have almost no coding skill). This works perfectly for me!

Topic Closed

This topic has been closed to new replies.

About this Topic