Call different archive page based on post type

Ok, I have quite a few CPT’s on my latest project. Most of the CPT’s are only used to display metabox content linking to pdfs, etc. I looked around and couldn’t find quite what I was looking for, but thought I could setup a function that calls the standard archive.php template if the post type is “posts” and if not it could call the archive-cpt.php file.

If anyone has seen something like that, or has set something like that up and wouldn’t mind sharing their code, it would be appreciated.

1 Answer
1

Take a look at the Template Hierarchy section of the Codex that concerns Custom Post types.

  1. archive-{post_type}.php – If the post type were product, WordPress would
    look for archive-product.php.
  2. archive.php
  3. index.php

What you are describing is built in, down to the file naming pattern– archive-cpt.php

To load the same template for all CPT archives use:

function not_post_archive_wpse_107931($template) {
  if (is_post_type_archive()) {
    $template = get_stylesheet_directory().'/archive-cpt.php';
  }
  return $template;
}
add_filter('template_include','not_post_archive_wpse_107931');

That will hijack all CPT archives so I would be very careful with it. It could lead to great frustration if someone can’t figure out why a CPT archive is not loading the expected template.

Barely tested. Possibly buggy. Caveat emptor. No refunds.

Leave a Comment