• Hi there!

    I’m having a heckuva time sorting out how to do this. I spent the better part of yesterday and today looking for a straightforward solution… but… here I am.

    OK… here’s my goal:

    I want to have the ability to choose a parent post (for the default ‘post’ post type) AND have the parent slug show up in the Permalink URL. Know what I’m saying?

    For example:

    >> Say, I have a post called: My Parent Post
    >>>> The URL, based on my Permalinks setup is something like: https://www.example.com/my-parent-post/

    >> Now, I create a child post, and call it: My Child Post (and *attach* it to the aforementioned Parent)
    >>>> I want the URL for it to be something like: https://www.example.com/my-parent-post/my-child-post/ rather than simply: https://www.example.com/my-child-post/

    It feels like an easy thing, but then my mind gets weird when I see Regular Expressions, and then I nap underneath my desk for a long time.

    So far, I was able to accomplish the first part (making the post type ‘post’ hierarchical and creating the box in the Post Editor to select a Parent), by using the following code:

    function my_hierarchical_posts($post_type) {
      if ($post_type != 'post') { return; }
      global $wp_post_types;
      $wp_post_types['post']->hierarchical = 1;
      add_post_type_support( 'post', 'page-attributes' );
    }
    add_action('registered_post_type', 'my_hierarchical_posts', 10, 1 );

    Please understand that I do not want to:

    1. Use Pages instead
    2. Use a Custom Post Type
    3. Nor, do I want any taxonomy slugs in the URL

    Thanks in advance!

    I’m going to contribute in the Forums here now for good Karma.

    Have a good one, and Happy Holidays to you! ??

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    To generate a hierarchical permalink any time the_permalink() or its relatives are used, use the “post_link” filter. The current post object is passed as the second parameter, so you can get the parent ID from it, and then the parent’s object and slug with that ID. Repeat through the hierarchy until the parent ID is 0, indicating a top level post.

    Adding the rewrite rule for a hierarchical request might look like this:
    add_rewrite_rule('.*/([^/]*)/?$', 'index.php?name=$matches[1]', 'top');

    I can’t guarantee it won’t screw up other requests, but it works for hierarchical requests in my very brief testing.

    You do realize that this is all done automatically with custom post types, right? A rhetorical question, you don’t need to explain yourself. I’m just pointing out how your decision to not use CPTs is making more work for yourself. No big deal if the above is all it takes ??

Viewing 1 replies (of 1 total)
  • The topic ‘default post hierarchy URL rewrite’ is closed to new replies.