I am woefully late to the party on Custom Post Types and only started using them quite recently, so apologies if my questions seems idiotic, but I can’t seem to find an answer to my question.
I’ve set up a custom post type called actors with a couple of custom field values, and (crucially), I’m using standard categories to separate these actors into men, women and children listings:
'taxonomies' => array('category', 'post_tag')
…since I thought that would be a much cleaner and neater way of… well, categorizing the actors. However, I’m completely stumped at how to actually display these categories in any way, shape or form.
I have a custom archive-actors.php
file which displays all of the actors, but I want to be able to filter them by category; e.g. only display the men. However if I guess at a standard URL like mysite.com/category/actors/men
I just get
Sorry, but there aren’t any posts in the Men category yet.
The same thing happens if I just try mysite.com/category/men
– in neither case is it using the archive-actors.php
template, either.
Can anyone help clear away my fog of dull-mindedness and point me in the right direction so I can filter out these pesky actors?
Edit:
As @mrwweb alludes to below (and I forgot to mention I had tried), the following can be added to the functions.php
file:
function query_post_type($query) {
$post_types = get_post_types();
if ( is_category() || is_tag()) {
$post_type = get_query_var('actors');
if ( $post_type ) {
$post_type = $post_type;
} else {
$post_type = $post_types;
}
$query->set('post_type', $post_type);
return $query;
}
}
add_filter('pre_get_posts', 'query_post_type');
…as referenced here which does work, insofar as it will display my categorised custom post types on the regular archive.php
page, but doesn’t utilise my archive-actors.php
, which is key.
You can force use of your template for categories with the
category_template
filter:adapted from Filter Hierarchy in codex.
That’s the expected behavior of category archives. As found here on the Support forums the following snippet should resolve your issue (just change “article” to your post type):
UPDATE: Gah. I grabbed the wrong snippet. I meant to use this one.
Alternatively, what you can do is just add a new wp_rewrite rule to create a new url structure for displaying only posts in a given cpt and category. Something like the .gist I posted here:
[edit: can’t embed .gists so here’s the code and linky ]
Taxonomy Templates
https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/#custom-taxonomy
When your category taxonomy slug is “actors-category”:
Make it from category template: taxonomy-actors-category.php