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')) { return; } $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
- We added an action on WordPress hook pre_get_posts to modify the wordpress query before it gets executed.
- 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.) - 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.