0

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'.

/services/gardening/leeds

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

/services/gardening?location=leeds

but still show as the following in the browser:

/services/gardening/leeds

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

Thanks

0

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.

| 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.