Is it possible to have a template that works on multiple categories where the link address contains the specific category?
-
19-04-2021 - |
Question
This question is for a very specific refinement on the use of WordPress template files. The refinement would work similarly to how default archive.php and variants work, but we would like to have a second template that has the same mechanism for querying the desired category through the link address.
The model is a wood site where some people like to browse through the default template style, but others would prefer to just see a list of links.
The goal is to create one template where the category would be passed to the template through the link, instead of having to create a new list template for each category.
Solution
Why not using a meta field ? That way you can determine which template to use for specific category template.
In your loop just get the current category that you are trying to load:
if( have_posts() ) {
while( have_posts() ) {
the_post();
$meta_value = get_post_meta( get_the_ID() , 'meta-field', true );
if($meta_value == 'template1') {
//I prefer using this method. Create folder templates with file content-template1.php where you can design your content. That way it is way more clear.
get_template_part('templates/content','template1');
// or you can use this method
the_title();
}
}
// Very Important
wp_reset_postdata();
}