0
votes

I'm struggling to get my custom post type to use my custom archive template, hopefully someone can see where I'm going wrong and help me get back on track please?

Here is the code I've used to create the custom post type:

add_action( 'init', 'news_post_type' );
function news_post_type() {
    register_post_type( 'news',
    array(
      'labels' => array(
        'name' => __( 'News' ),
        'singular_name' => __( 'News' )
      ),
      'capability_type' =>  'post',
      'has_archive' => true,
      'hierarchical' => true,
      'public' => true,
      'supports' => array('title','editor','excerpt','trackbacks','custom-fields','revisions','thumbnail','author','page-attributes',)
    )
  );
}
register_taxonomy( 'news_category', 'news',array('label' => __( 'Categories' ),'rewrite' => array( 'slug' => 'news/category' ),'hierarchical' => true, ) );

Which is great and the URL returns: www.mysite.com/news/category/%the_category% just like I want.

The problem is that I want each of the categories in this CPT to use my custom template, but when I create a file called archive-news.php it is ignored. However if I create a file called archive.php then it works but obviously this is applied to all other post archives which I don't want.

Am I not naming the template file correctly? Is there an error in how I've created the CPT?

If anyone can help that would be greatly appreciated.

Many thanks

2
codex.wordpress.org/Category_Templates category-slug.php, category-ID.php, category.php, archive.php, index.phpline88
Renaming the file to category-news.php didn't work either :(Ordog
try id of the category, or in your archive.php do something like this <?php if (is_category('Category A')) : get_template_part('mycustomtemplate') endif;?> developer.wordpress.org/reference/functions/get_template_partline88
I can't use the category ID because there are too many, plus this is likely to expand as the site grows so it will need me to continually edit the file to add these in.Ordog
Using category-slug.php is the same as using category-id.php because category slug must be unique accros the site. Try using is_category() to echo out custom template for the custom category, also try post-news.php for a single post, just to check if category is working properly...i think you missed rewrite => array('slug' => 'news') part in your cpt $args, try adding in to your register_post_type arguments arrayline88

2 Answers

0
votes

i have check with your code as its working properly on my side. i think you checking on detail page which single-$posttype.php file.

0
votes

Using taxonomy template worked in this instance, so naming my file taxonomy-news_category.php allowed me to create my own template for all categories in my custom post type.

I also found that having a page named the same as the custom post type was causing issues too. So in summary, rename the page or use the taxonomy template as above.