0

Does anyone know how to achieve different parent pages for posts?

I've managed to code a Custom Post Type that sits under a specific parent page, but I want the option to change this from post to post.

Example;

  • /page-1/custom-post-1/
  • /page-1/custom-post-2/
  • /page-2/custom-post-3/
  • /page-2/custom-post-4/

The final result would be URL structure like the above, but all posts sitting on one archive page.

I know by default this isn't possible as posts are non-hierarchical.

Thanks

6
  • Set the hierarchical parameter to true in your register_post_type args. You will get the option to select parent post in post edit scree,
    – Abhik
    May 16 at 10:52
  • 1
    are you asking how to set up the UI? Or is it the permalinks you're asking about? Or are you starting from scratch? WP assumes if a post type has hierarchy that its parent is of the same type but this is just an assumption and not enforced in the DB, and even used by WP itself for attachments and revisions etc, though the default rewrite rules weren't always written for this.
    – Tom J Nowell
    May 16 at 10:54
  • Hey @TomJNowell, it's more for the permalinks and redirects. Coding the UI isn't a problem, but it's just ensuring the URL structure comes out as intended.
    – crgn
    May 16 at 14:05
  • Hey @Abhik, that would only allow me to set a parent of the same post type. I want my custom post type to have a parent page.
    – crgn
    May 16 at 14:06
  • is this a page the user has chosen or is this page something you created with a page template listing your post types? AKA are you trying to build a post type archive on a page with a page builder but now your custom posts have the wrong URL?
    – Tom J Nowell
    May 16 at 14:24

1 Answer 1

0

This should be in a comment, but can't format much in there.

  1. Create a relationship between your CPT and Page. For example, create a custom taxonomy for your CPT and programatically add the pages as terms. Or, you can even create a meta field.

  2. Create a placeholder for the URL while registering the CPT. For example 'rewrite' => array( 'slug' => '%cpttag%'),.

  3. str_replace the placeholder with page slug you get from term/meta using post_type_link.

  4. Flush the permalinks (Just hitting Save on Permalinks Settings page will do it)

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.