Is there a proper way for wordpress rewrite and template include modification?

Question

I’m currently trying to modify the permalinks for WP which is why I’m using the add_rewrite_rule to setup the query_vars however I’m currently having doubts as to how I should properly get the target template.

Permalink: domain.com/cpt1/term1_of_ctx1/term1_of_ctx2

Target template: taxonomy - ctx2 - term1_of_ctx2.php

currently using the rewrite rule below:

add_rewrite_rule('^cpt1/([^/]+)/([^/]+)/?$', 'index.php?ctx2=$matches[2]&ctx1=$matches[1]&post_type=cpt1&taxonomy=ctx2&term=$matches[2]','top' )

By default this gives me term archive template for term1_of_ctx1, but I need the term1_of_ctx2 term archive template.

So currently I ‘redirect‘ wp to use the term1_of_ctx2 term archive template by checking if the term1_of_ctx2 term exist in the query_var then tapping into template_include hook and giving it the term1_of_ctx2 term archive template location.

All is ‘fine and dandy’ until I have to think about the possibility of a new term under ctx2 tax which means I have to use the ctx2 tax template if the specific term template hasn’t been created yet (out-of-box WP template traversal).

To answer this I had to create IF statements to specify to use the taxonomy template file if the target term template file doesn’t exist before tapping into the template_include hook which to me seems like ‘reinventing-the-wheel‘ and hacky approach..

so I’m wondering if there’s a better and a right way to do this or if there’s actually a hook i’m missing which can leverage out of the out of box WP template traversal instead of manually implementing it especially for for non-existent term template files.

I’ve come across {$type}_template however the notes like this one here seems redudant to the oob WP hierarchical template traversal to me (clearly, I don’t have much idea about it).

0
ardv 2 years 2020-12-15T20:10:31-05:00 0 Answers 6 views 0

Leave an answer

Browse
Browse