I'm working on passing a get parameter to a single custom post type in a clean url. So for instance there would be the custom post type 'services' which would have the single post 'gardening'.


which would translate to the following so the variable is accessible on the template:


but still show as the following in the browser:


I just wondered if anyone had done that before using custom post types?



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;

    , "index.php?$query_var=\$matches[1]&location=\$matches[2]"
    , "top"

after adding this in your plugin, you need to flush rewrite rules once :

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.

| improve this answer | |
  • Many thanks for your help Kaperto! Would that work for /services/gardening/leeds or perhaps /services/gardening/location/leeds as well? I've tried it after flushing the rewrite URLs but it seems to redirect to the contact page rather than a 404 page – R14523 Nov 11 '19 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.