Disable search, author, attachment, and date-based archives

If the WordPress site you’ve built doesn’t make use of search, author archives, attachment links, or date-based archives, those pages are generated and people can stumble across them. So, just turn them off, right?

Unfortunately, to the best of my knowledge, there isn’t a simple switch for that. Instead, you have to go about it another way.

/*****
  Disable attachment, search, author, daily archive pages
*****/
function disable_archives_and_more(){

  global $wp_query, $post;

  if (is_author() || is_attachment() || is_search() || is_year() || is_month() || is_day()) :
    $wp_query->set_404();
  endif;

  if (is_feed()) :
    $author 	 = get_query_var('author_name');
    $attachment  = get_query_var('attachment');
    $attachment  = (empty($attachment)) ? get_query_var('attachment_id') : $attachment;
    $year        = get_query_var('year');
    $month       = get_query_var('month');
    $day         = get_query_var('day');
    $search      = get_query_var('s');

    if (!empty($author) || !empty($attachment) || !empty($search) || !empty($year) || !empty($month) || !empty($day)) :
      $wp_query->set_404();
      $wp_query->is_feed = false;
    endif;
    
  endif;
}
add_action('template_redirect', 'disable_archives_and_more');

What this does, it returns a 404 for any of those template types, and disabled it from generating a RSS/Atom feed.

I’ve used this in dozens of projects that are largely brochure sites, with new sections that’s updated every few weeks, and hardly warrant search, or extensive archives.