2

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

5

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.

6
  • Well, what I'm not wanting to do is create an archive-{post_type}.php template for each CPT. I'd like to use one archive-cpt.php file for all CPT's. Since they don't fall under "posts" I wasn't sure if there was a way to assign an archive-cpt.php file to any registered post type that is not "Posts"
    – mtuttle
    Commented Jul 26, 2013 at 14:06
  • 1
    Give me a minute. You can do that with a filter.
    – s_ha_dum
    Commented Jul 26, 2013 at 14:07
  • Awesome! I thought I could but wasn't sure. Seems like it might be an easier way to go if there are multiple CPT's. Plus my client who can't create templates (at least I don't trust them to) can then create new CPT's via a plugin I've installed.
    – mtuttle
    Commented Jul 26, 2013 at 14:13
  • Tried that filter, but now all archive pages are coming up blank. I'll keep playing with it. Thanks for the start!
    – mtuttle
    Commented Jul 26, 2013 at 14:52
  • I'm an idiot. Sorry. I think you want get_template_directory not get_template_directory_uri
    – s_ha_dum
    Commented Jul 26, 2013 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.