Site logo

Archived topic

Exclude Posts With Specific Tag From Category Archive

4 replies · Started by Shane on May 5, 2021

Viewing posts 1–5 of 5

Hey All

I'm trying to remove posts with a specific tag (ID is 25) from my category archive pages (all over the site). I've tried a number of different snippets of code from this forum. The below code got me the closest removing the posts with the tag, but ended up breaking my homepage.

add_filter('request', 'filter_tag_loop');
    
function filter_tag_loop($params) {
    
$params['tag__not_in'] = array( 25 );
    
return $params;
    
}

This post -> https://generatepress.com/forums/topic/exclude-posts-with-specific-tag-from-blog-archive-page/ was close to helping as well, but was only meant to filter posts on the homepage. My category archive isn't on the homepage.

Thank you!

Hi there,

You can go with pre_get_posts.

Example:

function excludeTagId($query) {
  $tag_Ids = array(
    25, 24, 23
  );

  if ($query->is_main_query() && ! is_admin() && $query->is_category() ) {
    $query->set( 'tag__not_in', $tag_Ids );
  }
}
add_action('pre_get_posts', 'excludeTagId');

25,24 and 23 are tag IDs. You can add more.

Boom, worked perfectly.

You are awesome!

Marking as resolved!

No problem. glad you got it sorted. :D

This archived topic is closed to new replies.