Ready to get started?Download WordPress


Exclude certain categories from search results page (5 posts)

  1. Agent D
    Posted 4 years ago #


    I've been trying to find a way to customize search.php to exclude certain categories to be displayed. Is it possible to do this without plugins? Many thanks in advance!


  2. henkholland
    Posted 4 years ago #

    Try in search.php to replace this:

    <?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
    <div class="post" id="post-<?php the_ID(); ?>">
    <?php endwhile; ?>

    with this:

    <?php query_posts('category_id=#&showposts=#');?>
    <?php $posts = get_posts('category=-3&numberposts=0&offset=0');
    	foreach ($posts as $post) : start_wp(); ?>
    <?php endforeach; ?>

    Category 3 should be excluded. I did not try category=-3,-6 etc

  3. Mark / t31os
    Posted 4 years ago #

    Looks a little overkill for just excluding a category..

    You could merge your category parameter with the existing query, like so..

    if(!$wp_query) global $wp_query;
    query_posts( array_merge( array( 'category__not_in' => array(123) ) , $wp_query->query ) );

    Where 123 would be the category ID.

  4. matthewpaul
    Posted 4 years ago #

    <?php query_posts("cat=-1,-2,-3"); ?>
    <?php if(have_posts()) : ?>

    appears to work as well.
    1, 2, and 3 are the category IDs.

  5. Mark / t31os
    Posted 4 years ago #

    Yes but you're not preserving any existing queried vars, you're just delcaring new ones, over-riding any that exist for the particular parameter you're declaring.... (in this case category include/exclude)..

    Which is fine, as long as there were no other query vars present that needed preserving, which is why i tend to favor the merge approach, it's just a catch all for when users "may" have other vars in the query...

Topic Closed

This topic has been closed to new replies.

About this Topic