How can I make rewrite rules for a custom post type?

Question

I’m trying to create rewrite rule which will work this way: when user enters URL site.com/projects/projectname/cityname it should work as site.com/?projects=projectname&city=cityname, where: cityname – GET-parameter “city”, projectname – name of the page, projects – custom post type.
For example: site.com/projects/testproject/london should be the same as site.com/?projects=testproject&city=london.
I found a few examples on WordPress Codex and stackoverflow, but these examples is not working. Probably, I’m doing something wrong.
One of the examples which I’ve tried and it’s not working:

add_action('init', 'do_rewrite');
function do_rewrite(){
    add_rewrite_rule( '^(projects)/([^/]*)/([^/]*)/?', 'index.php?projects=$matches[1]&city=$matches[2]', 'top' );
    add_filter( 'query_vars', function( $vars ){
        $vars[] = 'city';
        return $vars;
    } );
}
0
YRWD 4 months 0 Answers 13 views 0

Leave an answer