1

We have rewrite rules as:

add_action( 'init', function() {
    add_rewrite_rule( 'app-api/v2/ecommerce/([a-z0-9-]+)[/]?$', 'index.php?p=$matches[1]&post_type=product' );
} );

for the URL - www.domain.com/app-api/v2/ecommerce/14. We load a custom template using template_include hook for custom rules.

The above works fine, but for some specific reasons the client wants to make use of query variables so that the new URL will be of the form www.domain.com/app-api/v2/ecommerce?pid=14

What I am trying to achieve is something like this, which doesn't work.

add_action( 'init', function() {
   $id = $_GET['pid'];
   add_rewrite_rule( 'app-api/v2/ecommerce', "index.php?p={$id}&post_type=product" );
} );

What is the correct way to add a rewrite rule with dynamic query variables?

1
  • Your first rewrite rule doesn't match the format you gave.. did you mean the URLs are like www.domain.com/app-api/v2/ecommerce14 or www.domain.com/app-api/v2/ecommerce-14 now?
    – mozboz
    Jul 30, 2020 at 9:26

2 Answers 2

0

First of all, Your code does not work because rewrite rules need to be flushed ( function flush_rewrite_rules ), and they need to be flushed for every $id change. Generally this is very bad idea, for performance reasons.

You should add rewrite rule only with post_type=product, as You want to pass "p" as $_GET parameter

add_rewrite_rule( 'app-api/v2/ecommerce', "index.php?post_type=product" );

then in template_include hook function look for $_GET['pid'] and based on it, choose Your template

Hope, it helps

0

From what you want to do it sounds like the destination URL has not changed, but the format of the URL's you want to rewrite from has changed, is that correct?

So URL's like this:

www.domain.com/app-api/v2/ecommerce/14

Should now look like this:

www.domain.com/app-api/v2/ecommerce?pid=14

If so this why not just slightly change the format from your original rewrite rule if it was working, to:

add_rewrite_rule( 'app-api/v2/ecommerce?pid=([a-z0-9-]+)[/]?$', 'index.php?p=$matches[1]&post_type=product' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.