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).
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).
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');
&state=state$matches[2]
– Sally CJ Commented Mar 14, 2019 at 18:43state{slug}
, e.g.state-one
,statetwo
, etc.? I.e. the slug always starts with the textstate
? If so, then the&state=$matches[2]
in the secondadd_rewrite_rule()
should be&state=state$matches[2]
– Sally CJ Commented Mar 14, 2019 at 19:03/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