0

So I am looking for a better way or the correct way to rewrite WordPress' url query mydomain?p=123 to show as mydomain/parent/child/ or mydomain/parent/child/gchild

I have tried to force change the post_name but that didn't work. Core overrides with an appended of -2, -3, etc. So I wanted use the title of my posts and its children to show in the url as:

mydomain/order123/1/1

my posts are set to hierarchy so I can enable the parent/child structure in WP.

So my posts are titled like:


ORDER123 << parent
- 1 << child
-- 1 << grand child
-- 2
- 2
-- 1
ORDER124
- 1
- 2
-- 1
-- 2
-- 3

So my url I desired to look like: mydomain/order123/1/1

So in order to do this I am attempting to use wp_rewrite_rule example: https://codex.wordpress.org/Rewrite_API/add_rewrite_rule

function custom_rewrite_basic() {
  global $post;
  $ancestors = get_post_ancestors( $post->ID);
  $ancestors = array_reverse($ancestors);
  $url = "";
  foreach ($ancestors as $ancestor):
   $url .= $ancestor.'/';
  endforeach;


  add_rewrite_rule('^'.$url.'?', 'index.php?page_id =$post->ID', 'top');
}
add_action('init', 'custom_rewrite_basic');

What am I doing wrong?

Your Answer

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

Browse other questions tagged or ask your own question.