Pass parameter to custom post type single while keeping clean url

you can add this parameter in URL with this code to put after registering the custom post type :

add_rewrite_tag('%location%', "([^&]+)");


$slug =      get_post_type_object("services")->rewrite["slug"];
$query_var = get_post_type_object("services")->query_var;

add_rewrite_rule(
      "$slug/([^&]+)/([^&]+)$"
    , "index.php?$query_var=\$matches[1]&location=\$matches[2]"
    , "top"
);

after adding this in your plugin, you need to flush rewrite rules once :
https://codex.wordpress.org/Function_Reference/flush_rewrite_rules

then you can read the location with get_query_var("location"). the magic of wordpress is that this code works with URL /services/gardening?location=leeds and /services/gardening too.

Leave a Comment