Site icon Web Niraj

WordPress Loop – Include / Exclude Tags from Template Files

If you want to filter certain posts by tags in your WordPress theme, here is a simple way to do so before executing the WordPress loop. This method lets you exclude posts that contain certain tags, or you can easily change the code to include post with certain tags instead.

Solution

//	Modify the query
$query_string['tag__not_in'] = array(1,4,5);
query_posts( $query_string );

//	WordPress Loop
if (have_posts()) :
	while (have_posts()) : the_post(); update_post_caches($posts);
		//	Display posts here
	endwhile;
else :
	//	No posts found
endif;

Modification

If you want to include certain tag IDs, you only need to change one line of the code.

Change:

$query_string['tag__not_in'] = array(1,4,5);

To:

$query_string['tag__in'] = array(1,4,5);
Exit mobile version