0

The documentation for template hierarchy for custom post types (CPT) includes:

  1. Either for the CPT itself (archive-cptname.php)
  2. Or for custom taxonomies (taxonomy-taxonomyname.php)
  3. Or for overall categories (category-catname.php)

But it doesn't include the obvious "CPT, with global categories". What would that be? I tried something like archive-cptname-categoryname.php, but this doesn't work. Any pointers?

2

Because there's no such thing.

If you use the same taxonomy for two or more post types then there isn't separate archives for each post type in that taxonomy's terms. There's a single archive for that taxonomy that lists posts of both post types. This might not work for built in taxonomies (categories and tags) though, as they are configured to only display posts. To display your post type on the category archive you'll need to use the pre_get_posts filter to add it:

add_filter(
    'pre_get_posts',
    function( $query ) {
        if ( $query->is_category() ) {
            $query->set( 'post_type', [ 'post', 'cptname' ] );
        }
    }
);

If you need separate archives for categories for each post type, then you need to register a separate taxonomy for your post type. Something like cptname_category. They won't share terms, but they will have separate archives.

6
  • Thank you for this, @Jacob. Wish the documentation made this clear. Anyway, if I do add the above code, what will my template be called? Alternatively I suppose I could just do the Category template and have an IF condition inside to check for the URL or something? – Khom Nazid Aug 9 '19 at 1:10
  • 1
    The template names are always the same. If you’re browsing categories it’s category.php, with the same fallbacks. But if you need separate archives, use separate taxonomies. That’s what they’re for. – Jacob Peattie Aug 9 '19 at 1:26
  • Thanks. But then we end up with separate taxonomies with exactly the same names across various CPTs. Around 50 categories and subcategories--this is a magazine. It has sections of the magazine (CPTs) which all carry material related to the same themes (categories). – Khom Nazid Aug 9 '19 at 2:33
  • Sorry, the code above doesn't seem to work. The line ` $query->set( 'post_type', [ 'post', 'cptname' ] );` -- in this line, I understand post_type is to be replace by my CPT name. But is the word cptname a fixed word? (I think it may be the other way around -- cptname is where I'm to enter one of my CPT names, yes? How about enabling these categories for all CPTs?) – Khom Nazid Aug 9 '19 at 2:55
  • 1
    I copied cptname from your question. It should be substituted with your post type name. To add more post types add them to the array: [ 'post', 'cptname', 'cptname2' ] etc. – Jacob Peattie Aug 9 '19 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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