So if I have a template file called category-whatever.php, and if someone clicks on the thumbnail representing “whatever” on my home page, WordPress looks for that category-whatever.php file
Yes. If category-whatever.php doesn’t exist, WP falls back to using category.php and, as a last resort, index.php.
Well, I tried it but it didn’t work. I have a category called ‘tables’ and I have a file called category-tables.php, but when I clicked on the post falling under the category ‘tables’ I still ended up in index.php. What could I be doing wrong?
So when I set a breakpoint in Template-Loader and it goes through all those elseif’s to find the template, it ends up with
else :
$template = get_index_template();
endif;
The only flag I can see being set is $single which is set to 1 at that time. But I don’t have a single-tables.php file.
-
This reply was modified 9 years, 3 months ago by
hyacinthus. Reason: a bit more information
One minor clarification on esmi’s post. In between category.php and index.php in the template chain is archive.php.
The category template chain is used when multiple posts in a certain category are returned by the query. When only one post is returned, the single template chain is used. The only template in common between the two is the last resort index.php. If you need special category handling on single type templates, it needs to handled through template code. The WP template loader is not going to be helpful in this situation.
I think I’m getting closer to having it work. I think I had the wrong href in my link on the front page.
But if I need special category handling on single type templates, would I then create a single-tables.php file? And then maybe do my own loop there? Sometimes I get confused by what has to be done within the loop and what can be done outside. Any tutorials lurking around for that?
Sorry, I’m unaware of any related tutorials. They may exist, I just don’t know about them.
Any category as part of a single-*.php template name will not work. Only post types and IDs work with single names. What I meant is on the normal single post template, you could add an if/else conditional structure where if the current post’s categories includes “whatever”, then handle output a particular way, else do the normal single output. In essence, two templates in one.
Determining if a category is applied takes a bit of coding by itself. You can get all the categories with wp_get_post_categories(), but the category you are looking for can be anywhere in the returned list. Thus you need to loop through all the listed terms to see if any of them are “whatever”.
Thanks for the extra clarification. I can see that it’s going to take some time to get up to speed on how WordPress works. But I’m getting there.
No problem!
I don’t wish to be discouraging, but after 5 years working with WP, I still don’t fully understand how it works! It’s OK though. As you gain experience, you learn what you need to learn 🙂