Search code examples
phpregexwordpressmod-rewrite

Wordpress Rewrite_Rule to allow '/page/value'


I have a page called 'all-products' on Wordpress, and I want to get products using id in the url as domain.com/all-products/4382zcxs2133

function add_my_var($public_query_vars) {
    $public_query_vars[] = 'routeparam';
    return $public_query_vars;
}

add_filter('query_vars', 'add_my_var');

function do_rewrite() {
    add_rewrite_rule('all-products/[a-zA-Z0-9]/?$', 'index.php?pagename=all-products&routeparam=$matches[1]','top');
}

add_action('init', 'do_rewrite');

Then, when I tried using $wp_query->query_vars['routeparam'], it says 'undefined index'.

When I var_dump($wp_query->query_vars), I can actually see the value in an index called page but that only works for numbers. If I use letters and numbers instead, I get 404 error.


Edit:

/all-products/213213 - works

/all-products/ - works

/all-products/21321dsa3fsa - doesn't work

I tried the regex on a fiddle, it works, but on Wordpress in add_rewrite_rule, it doesn't work.


Edit 2:

I've commented out my write rule line, and it looks like it can still access product/123 so somehow, my rewrite rule is not registering.

I tried var_dump($wp_rewrite) and I can confirm that my rewrite rule is registered but I believe that default wordpress pagination ('pagination_base' exactly) may cause this.

Because when I comment out add write rule and visit the url through /all-products/123, I can still access the page without a 404 and I can see that '123' value I have provided is shown as 'page' in $wp_query->query_vars.


Solution

  • You can use

    'products(?:/([a-zA-Z0-9]+))?/?$'
    

    or if this part is always at the beginning, add ^:

    '^products(?:/([a-zA-Z0-9]+))?/?$'
    

    Note the + and (...) parentheses around [a-zA-Z0-9]+ that form Group 1 and its value will be used via $matches[1].

    And Do not forget to flush and regenerate the rewrite rules database after modifying rules. From WordPress Administration Screens, Select Settings -> Permalinks and just click Save Changes without any changes..