0

I need foo-bar to become foo/bar instead:

//domain.com/foo-bar   »   //domain.com/foo/bar


I'm rebuilding a website that is currently in a home-brew CMS. They have a few pages with children, but the parent page URL does not match the children. The parent URLs were changed but the children were never updated.

Expected Structure:
//domain.com/parent/
//domain.com/parent/child

Current Structure:
//domain.com/parentpage/     (changed from /parent/)
//domain.com/parent/child

I could just create a page for each but I'm trying to avoid having empty/unused pages.

What I'm hoping to do is just create //domain.com/parent-child/ and rewrite the URL to match, but I can't get my rules to take priority over an existing rule.

Maybe I'm misunderstanding what rewrites can accomplish?


add_rewrite_rule

Matched Query:

pagename=foo-bar&page=

My Attempts: I expected somethig like one of these to be my solution, but I've tried a dozen different minor variations without success:

add_rewrite_rule( '^foo/bar', 'index.php?pagename=foo-bar', 'top');
add_rewrite_rule( '(foo)/(bar)', 'index.php?pagename=$matches[1]-$matches[2]&page=', 'top');

Default rule my page is matching:

add_rewrite_rule( '(.?.+?)(?:/([0-9]+))?/?$', 'index.php?pagename=$matches[1]&page=$matches[2]')
  • What about creating a category "foo" with page name "bar"? – Swen Apr 18 '17 at 22:05
  • That could work too, but seems more confusing than just having an empty page. – H21 Apr 19 '17 at 16:36
  • Your first attempt works as expected for me, latest WP, no plugins, 2016 theme. – Milo Apr 19 '17 at 17:07
  • I noticed my rewrites were not flushing when I expected them to so that's a possibility. But I actually just got a more dynamic version working based on a post you answered. =) wordpress.stackexchange.com/questions/250837/… – H21 Apr 19 '17 at 17:36
1

This rule is what I ended up with after finding this post: Understanding add_rewrite_rule

add_rewrite_rule( '^foo/([^/]*)/?$', 'index.php?pagename=foo-$matches[1]', 'top' );
0

First of all, you can change rules not only with add_rewrite_rule but also with a filter(s) (one - general I am using in all common cases is rewrite_rules_array). You will receive an array of rewrite rules (and you expect to return it back), but you can change it slightly.

And (minute of advertisement) - you can also use debug bar and debug bar rewrite rules panel to check your rules against your test URLs to see priority/matches etc. I am the author of this plugin (debug bar rewrite rules panel) and will be glad for a feedback.

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.