-
Brent Wilson
I have a custom post type with a taxonomy of years (for example, 2021, 2022, 2023).
I have a template element that I want to apply to any single posts of this post type with the taxonomy of 2022.
I have a different template element that I want to apply to any single posts of this post type with the taxonomy of 2023.
So far, this is pretty straightforward to do.
The problem is when I have a post with both the 2022 and 2023 taxonomies. In this case, I want the 2023 template element to apply, not the 2022 template element.
How do I set up the display conditions to make this happen? It seems like there is some conflict in this situation.
-
Fernando
Hi Brent,
First of all, usually, creating taxonomies that are named by dates is a bad idea. The slugs for years for instance are reserved by WordPress for an archive page that retrieves all posts of a specific year. Make sure the the slug of your taxonomies, though named after years, won’t be actual years. Try
2021-a,2022-aetc. for instance.To clarify, do some of your posts have both 2022 and 2023 taxonomies? If so, for these instances, you can opt to override the display rule settings through a filter –
generate_element_display. Reference: https://docs.generatepress.com/article/generate_element_display/You’ll need to create a logic to check if a CPT has both 2022 and 2023, and then display the Element or not.
-
Brent Wilson
I will take care of the taxonomy slugs.
Yes, some posts have both 2022 and 2023 taxonomies (some also have a 2021 taxonomy). In those cases, I want them to use the 2023 content template element (ID 31580).
But if there is no 2023 taxonomy, but a 2022 taxonomy is present, I want them to use the 2022 content template element (ID 30090).
And if there is no 2022 taxonomy, but a 2021 taxonomy is present, I want them to use the 2021 content template element.
I am not a PHP expert. Can you give me a bit of guidance regarding how to format the necessary filter(s) for this functionality?
Also, when in the edit mode for a content template element, there is a dropdown in the right side settings for “Apply To”. How is this different from the display rules down below?
-
Fernando
Try something like this:
add_filter( 'generate_element_display', function( $display, $element_id ) { if ( 100 === $element_id && is_single() && has_category(array(30090, 31580)) ) { $display = false; } else if ( 101 === $element_id && is_single() && has_category(array(30090, 31580)) ) { $display = true; } return $display; }, 10, 2 );Replace 100 with the ID of the 2023 taxonomy Element ID and 101 with the 2022 Element ID.
Getting the Element ID: https://share.getcloudapp.com/YEuDdrnQ
Adding PHP: https://docs.generatepress.com/article/adding-php/#code-snippets
Repeat the steps for other instances like 2022 and 2021. Just replace the Taxonomy IDs in the code.
- You must be logged in to reply to this topic.