i have this codes in my wordpress plugin to add custom url rewrites:

add_action('init', function() {
    add_rewrite_rule( '^cities/(.*)/browse/(.*)/(.*)/(.*)/(.*)',
        'top' );

    add_rewrite_rule( '^cities/(.*)/browse/(.*)/(.*)/(.*)',
        'top' );

    add_rewrite_rule( '^cities/(.*)/browse/(.*)/(.*)',
        'top' );

    add_rewrite_rule( '^cities/(.*)/browse/(.*)',
        'top' );

    add_rewrite_rule( '^cities/?([^/]*)/browse',
        'top' );


}, 10, 0);

how can i rewrite (.*)/(.*)/(.*)/(.*) and get $matches as array ? first element of $matches is city_name variable value and the rest are cat_name array elements.

now everything works but i know the code can be a lot smaller.

  • 1
    Your rules seem to be weird. With them /browse/a/b will get the exact same output as /browse/b/a which is probably wrong, at least from url esthetics POV. Nov 30 '17 at 20:02
  • @MarkKaplun yes /browse/a/b can works as /browse/b/a but i'll check if a is parent of b later in a function, if it's not user will be redirected to 404 page. Dec 2 '17 at 12:57

With all part optional with ?, you obtain one rule to rule them all :


but the [] cannot work with the WordPress logic then you need to define the rewrite tag with a number. try that :

add_rewrite_tag("%cat_name.%", "([^&]+)");

  • I suspect you are going to get unknown index notices when not all the parts are there Nov 30 '17 at 20:03
  • I made some tests and the empty values don't throw notice. but the tests make me find that name with [] cannot work. I have edited my answer.
    – mmm
    Nov 30 '17 at 20:24
  • yeh I commented to the question... this is not the wordpress way o select multiple cats if that what he wants, Dec 1 '17 at 3:05
  • can u suggest a code to get more than 3 cat_names ? like 'index.php?city_name=$matches[1]&cat_name[]=$matches[x in rest]. in my own code i'm limited to 4 cat_name array elements. i need something unlimited. Dec 2 '17 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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