Exclude uncategorized posts from search and archive pages

In my WordPress site I want to prevent any uncategorized posts from showing up in site searches and in archive pages – including the front page of recent posts.

The only places that I want uncategorised posts to be visible are the actual posts themselves, and on the author archive pages, eg example.com/author/authorName

Read More

I have looked in vain for a plugin. I reckon there must be some custom php, but my skills are not that deep.

Any help or clues greatly appreciated!

Related posts

1 comment

  1. You have to exclude the category from the loop in your archive.php and index.php. This example uses category ID numbers, which you can find by going to Posts >> Categories. You’ll see the ID for each category.

    In your files mentioned above, find the loop

    <?php $query = new WP_Query( 'cat=-1' ); ?> // This is where you exclude. You can comma separate multiple categories : 'cat=-1,-2,-3' etc
     <?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
    
     <div class="post">
    
     <!-- Here is the post content - use whatever your theme is using -->
    
     </div> 
    
     <?php endwhile; 
     wp_reset_postdata();
     else : ?>
     <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
     <?php endif; ?>
    

    As for the search results, try this. This will go in functions.php (I haven’t tested it so let me know if there are issues).

    add_filter( 'pre_get_posts' , 'search_exclude' );
    function search_exclude( $query ) {
    
    if( $query->is_admin )
    return $query;
    
    if( $query->is_search ) {
    $query->set( 'category__not_in' , array( 1 ) ); // Category ID
    }
    return $query;
    }
    

    Please note: you can also comma separate the categories here by doing this:

    $query->set( 'category__not_in' , array( 1,2,3 ) );
    

Comments are closed.