I have a query string added to some urls which isn't pretty:
?city=Amsterdam
So i'd like to structure the url like: https://example.com/realpage1/realpage2/amsterdam/ or https://example.com/realpage1/amsterdam/ depending on the type of content.
And then get the variable with some htaccess like:
RewriteRule ^/(.*)/(.*)/(.*)$ ?city=$3
The page /aaa/bbb/ does exits. But the above gives a 404.
How can i achieve this in Wordpress? Thanks.
UPDATE: Following @pat's suggestion, and the code form the user-contributed-notes, i now have the below code. But, still a 404 is returned. What am i missing? Code is added to my child-theme functions.php by the way.
function wpdocs_flush_rules() {
$rules = get_option( 'rewrite_rules' );
if ( ! isset( $rules['(.*)/(.*)/([a-zA-Z-]{4,20})/?$'] ) ) {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
}
add_action( 'wp_loaded','wpdocs_flush_rules' );
function wpdocs_insert_rewrite_rules( $rules ) {
$newrules = array();
$newrules['(.*)/(.*)/([a-zA-Z-]{4,20})/?$'] = 'index.php?stad=$matches[3]';
return $newrules + $rules;
}
add_filter( 'page_rewrite_rules', 'wpdocs_insert_rewrite_rules' );
function wpdocs_insert_query_vars( $vars ) {
$vars[] = 'city';
return $vars;
}
add_filter( 'query_vars', 'wpdocs_insert_query_vars' );
.htaccess
to add rewrite rules to WordPress. There's an entire API provided for just that. Check out theWP_Rewrite
class, and have a look at the user-contributed notes which appears to have a quick recipe for how to create a URL rewrite. – Pat J May 15 '20 at 13:47