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/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/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?
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?
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
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' );
www.domain.com/app-api/v2/ecommerce14
orwww.domain.com/app-api/v2/ecommerce-14
now? – mozboz Commented Jul 30, 2020 at 9:26