skip to Main Content

I’m trying to work out how to hide a particular category (id=89) from my wordpress blog archive page. I want to be able to use specific blog posts with this category on another part of the site but i don’t want them to appear in any of the main archive pages (as a category link or show the posts themselves via the archive page). I have the following code on my page but i don’t know where and what to add to it to hide this id:

        <h3>Categories</h3>
        <?php
        $categories = get_categories( array(
            'hide_empty' => 1,
        ) );
         
        foreach( $categories as $category ) {
        
        // print_r($category);
        
        $category_link = get_category_link( $category->term_id ); 
        ?>
        <ul>
        <li><a href="<?php echo $category_link; ?>"><?php echo $category->name; ?></a></li>
        
        <?php
        }
        ?>
        
        </ul>
        </div>
```

2

Answers


  1. For the category list, modify your code like this:

    <h3>Categories</h3>
    <?php
    $categories = get_categories(array(
        'hide_empty' => 1,
        'exclude' => array(89) // Exclude category ID 89
    ));
     
    foreach($categories as $category) {
        $category_link = get_category_link($category->term_id); 
        ?>
        <ul>
            <li><a href="<?php echo esc_url($category_link); ?>"><?php echo esc_html($category->name); ?></a></li>
        </ul>
        <?php
    }
    ?>
    </div>
    

    To also exclude posts from this category in your archive pages, add this code to your theme’s functions.php file

    function exclude_category_from_archive($query) {
    if (!is_admin() && $query->is_main_query()) {
        if ($query->is_archive() || $query->is_home()) {
            $query->set('cat', '-89'); // The minus sign excludes the 
    
    category
            }
        }
    }
    add_action('pre_get_posts', 'exclude_category_from_archive');
    

    If you need to exclude multiple categories, you can modify the arrays like this:

    'exclude' => array(89, 90, 91) // For the category list
    

    $query->set('cat', '-89,-90,-91') // For the archive pages

    Login or Signup to reply.
  2. You can simply exclude the category in your get_categories args:

    <h3>Categories</h3>
      <?php
      $categories = get_categories( array(
          'hide_empty' => 1,
          'exclude' => 89,
      ) );
       
      foreach( $categories as $category ) {
      
      // print_r($category);
      var_dump($category);
      
      $category_link = get_category_link( $category->term_id ); 
      ?>
      <ul>
      <li><a href="<?php echo $category_link; ?>"><?php echo $category->name; ?></a></li>
      
      <?php
      }
      ?>
      
      </ul>
      </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search