0

I am using a hierarchal custom post type (post type is called locations, slug = location) in WordPress. Locations can be nested (country/state/city)

I have successfully added custom query vars :

add_filter('query_vars', function($vars) { $vars[] = "view"; return $vars; });

which I use to decide what data to show for the location.

For example, mysite.com/location/country/?view=facts or mysite.com/location/country/state/city/?view=events

All of which is working great.

But I want to be able to access it as:

mysite.com/location/country/facts

mysite.com/location/country/state/city/facts

I have been playing around with add_rewrite_rule but can't make it work. Not sure if my $regex or $query is the problem; regex isn't my strong suit.

add_rewrite_rule( '/(view)/g', 'index.php?post_type=locations?view=$matches[1]','top' );
2
  • URIs cannot contain more than one ?. Also view is nowhere found in the relative URI /location/country/facts - are you sure you want to search that and not... well... /facts$?
    – AmigoJack
    Commented Oct 19, 2022 at 11:44
  • "are you sure you want to search that and not... well... /facts$ ?" As I understand it I should be searching for the query var, which in this case is view. View can have several possible values of which facts is but one. Depending on the value of view= I show different content. All of which is working fine, its just the permalink that I am struggling with Commented Oct 19, 2022 at 13:13

1 Answer 1

0

Try add_rewrite_endpoint, it is actually much simpler

https://developer.wordpress.org/reference/functions/add_rewrite_endpoint/

https://make.wordpress.org/plugins/2012/06/07/rewrite-endpoints-api/

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Oct 21, 2022 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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