Building on my previous post about creating archive pages for custom post types, there’s another piece to add to the puzzle.
You archives pages will use the default index.php
template. If you want to use a different template, you’ll need to hook into the template_redirect
action to specify your template file. I like to use a file name like type-MY_POST_TYPE.php
(although that’s easily changed), using the function below.
function my_template_redirect() { if ( is_robots() || is_feed() || is_trackback() || is_single() ) { return; // run the default action } global $wp; $template = locate_template(array('type-'.$wp->query_vars['post_type'].'.php')); if ( $template ) { include($template); exit; } } add_action('template_redirect', 'my_template_redirect');
If you have an archive of article
posts, WordPress will try to use type-article.php
. If it doesn’t find the template file, it will fall back to index.php
. You can add as many additional template names as you like to the array passed to locate_template()
.