WordPress – hide posts with a certain tag

I have recently taken a look through the portfolio projects on my website. It is a nice walk down memory lane, but also a misrepresentation of what I do nowadays. It is also true about content I have created a long time ago, which is no longer up to date. It would be a pity to delete them, so I have come up with this solution to hide them by tagging.

The tag to use is hidden. You can use your own tags, but be careful to follow the rules for defining a tag in the global posts query.

The code

The simplest way to get this going is to add the following code in your theme’s functions.php file:

 * Hide posts which are tagged with 'hidden'
function hide_posts_tagged_as_hidden ( $query ) {
    // Apply this filter only for posts, if not in the admin area
    if ( 
		!is_admin() // must not be in the admin aread
		&& ( 
			$query->get('post_type') === 'post' || // queries posts
			( is_archive() && single_cat_title("", false) !== 'hidden' ) // do nothing if trying to view the content of the tag
	) {
		// Define the new tax query
        $new_tax_query = array(
			'taxonomy' => 'post_tag',
			'field' => 'slug',
			'terms' => 'hidden',
			'operator' => 'NOT IN',
		// Append to the existing list
		$query->tax_query->queries[] = $new_tax_query; 
		// Set the new list
        $query->set( 'tax_query', $query->tax_query->queries );
// Add the function on the pre_get_posts hook, with 999 to be among the last to execute
add_action( 'pre_get_posts', 'hide_posts_tagged_as_hidden', 999 );Code language: PHP (php)

The code above can surely be improved – so take your shot at it! 🙂