0

I need to create a rewrite rule that accepts 2 variables. I'm very new to this and am not sure If I'm even on the right track. If there is a better solution to what I'm trying to achieve, I'm open for suggestions.

The url should look like this: localhost/states/id/state-slug

Here is what I have:

function prefix_movie_rewrite_rule() {

add_rewrite_rule ( 'states/([A-Za-z0-9\-\_]+)', 'index.php? 
state_id=$matches[1]', 'top' );

add_rewrite_rule ( 'states/([A-Za-z0-9\-\_]+)/state([A-Za-z0-9\-\_]+)', 
'index.php?state_id=$matches[1]&state=$matches[2]', 'top' );

}

add_action( 'init', 'prefix_movie_rewrite_rule');

Using what I have, I'm able to get the first variable (state_id) but not the second (state).

7
  • Try with &state=state$matches[2]
    – Sally CJ
    Commented Mar 14, 2019 at 18:43
  • Not sure what you mean? Commented Mar 14, 2019 at 18:47
  • Are the post slugs in this format: state{slug}, e.g. state-one, statetwo, etc.? I.e. the slug always starts with the text state? If so, then the &state=$matches[2] in the second add_rewrite_rule() should be &state=state$matches[2]
    – Sally CJ
    Commented Mar 14, 2019 at 19:03
  • If not, then the /state([A-Za-z0-9\-\_]+) should probably be just /([A-Za-z0-9\-\_]+) so that it works with all slugs regardless the slug starts with the text "state" or not. I hope this helps you.
    – Sally CJ
    Commented Mar 14, 2019 at 19:20
  • The format i'm looking for is localhost/states/id/state-name so something like localhost/states/18/new-york Commented Mar 14, 2019 at 21:09

1 Answer 1

0

After lots of pulling my hair out I figured out the problem.

I needed to use the add_rewrite_tag() function to tell wordpress to allow my query vars.

function prefix_movie_rewrite_rule() {

add_rewrite_tag('%state_id%', '([A-Za-z0-9\-\_]+)');
add_rewrite_tag('%state%', '([A-Za-z0-9\-\_]+)');
add_rewrite_rule ( 'states/([A-Za-z0-9\-\_]+)/([A-Za-z0-9\-\_]+)', 'index.php? 
state_id=$matches[1]&state=$matches[2]', 'top' );

}

add_action( 'init', 'prefix_movie_rewrite_rule');
1
  • I see. And please don't forget to mark your answer as correct ("accept" it) so that people know the question has an accepted solution.
    – Sally CJ
    Commented Mar 16, 2019 at 8:12

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.