Rewrite only if no other matching page is found


I’m rebuilding a site in which I am required to change the URL structure for archive pages to something that WordPress doesn’t handle by default. I have a custom post type named product, which has a custom taxonomy product-category. I need to rewrite the /product-category/{term-slug} archive pages for this taxonomy to just be /{term-slug}.

So I am trying to make a rewrite rule that catches /{term-slug} pages, and rewrites them to /product-category/{term-slug}, ONLY if no other rules were matched.

I can do this to catch and rewrite these pages correctly:

function rewrite_product_archive() {
    add_rewrite_tag('%product-category%', '([a-z0-9-_]+)');
add_action('init', 'rewrite_product_archive');

With this, I can navigate to a /{term-slug} page and it will show the archive /product-category/{term-slug} page correctly. However, this now causes all actual pages to stop working and 404.

So I tried changing the third parameter in my rewrite from top to bottom, and doing a flush. This now makes my regular pages work again, but now the /{term-slug} rewrites have stopped working and they 404 now.

So essentially, I just need to follow the rewrite ONLY if no other rules were matched. Is that possible?

chrispytoes 4 months 0 Answers 10 views 0

Leave an answer