Hi!
I'd like to create 2 different layout to assign automatically in base of differnet category.
I see that is possibile to assign a layout only to posts/pages in general or to archives or to inidividual page.
Is not possible to assign it in base of post category or in base of specific taxonomies?
Thank you for your support
Hi, I'm not sure I understand what you mean by "in the base", but it sounds like you want to apply different Layouts on some posts based on the term(s) applied to that post. It is complicated, because multiple terms can be assigned to the same post. We offer a hook you can use in PHP to modify the Layout ID as needed, get_layout_id_for_render. Here is a very simple example:
function apply_layout_by_post_term( $id, $layout ){
global $post;
$term_a_layout = 9876;
$term_b_layout = 1234;
if( has_term( 'term-slug-a', 'category', $post->ID ) ){
return $term_a_layout;
}
if( has_term( 'term-slug-b', 'category', $post->ID ) ){
return $term_b_layout;
}
return $id;
}
add_filter('get_layout_id_for_render', 'apply_layout_by_post_term', 10, 2);
9876 and 1234 represent the numeric ID of the Layout you want to apply to the current post. You can see that this logic is very simple, and if multiple terms can be assigned to the same post it's not really manageable. For instance, what happens if a post has term a and term b? You have to handle all these combinations and edge cases.
Thank you Christian, I understand what you mean.
The problem is that I've 2 different trype of product and I need to assign them different layout.
I create these 2 types of product with 2 different forms and , of course, fields and values. Products are creatd by "vendors" so is impossible for me to set a layout for each single product.
I thought to manage it with "category product".
category a = vendor a
category b = vendor b
But I'm open to a better solution. Wha you suggest to manage this type of issue?
Products are creatd by "vendors" so is impossible for me to set a layout for each single product.
The code I provided will automatically display the correct Layout, regardless of which Layout is set for each Product (or not set). The code checks the terms applied to each Product before it renders the single Product page, and overrides any Layout selected in wp-admin. What are the Product Category term slugs, and what are the correct Layout IDs for each term slug? I can update the code to only affect Product posts, using the correct terms and Layouts.