WordPress – how to exclude specific tag posts from a tag archive page

WordPress will display all posts on a tag archive page which are tagged with that tag. Sometimes we want to exclude posts of more specific tags to reduce number of pages. Here is the code snippet example which we can refer to for this.

add_action('pre_get_posts', 'pre_get_posts_tag_exclude_some_tags');
function pre_get_posts_tag_exclude_some_tags ($query) {
  if (!is_tag() || !$query->get('tag')) {
  $tagobj = get_term_by('slug', $query->get('tag'), 'post_tag');
  $tagslugs_to_exclude = array('foo', 'bar');
  $tagids_to_exclude = array();
  foreach ($tagslugs_to_exclude as $oneslug) {
    $onetagobj = get_term_by('slug', $oneslug, 'post_tag');
    $tagids_to_exclude[] = $onetagobj->term_id;
  $query->set('tag__not_in', $tagids_to_exclude);

Steps involved

  1. We added an action on WordPress hook pre_get_posts to modify the wordpress query before it gets executed.
  2. In action code we ensured that we are on tag page (is_tag()) and query should be for displaying posts for the tag page ($query->get('tag')). This is to avoid modifying query for other wordpress queries (e.g. getting menu list, etc.)
  3. We used tag__not_in param in query object (type QP_Query) to ignore specific tags.

Note that this code may reduce your total number of pages for a tag archive page. But posts per page will remain same.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments