How much control do we have over CPT rewrite slugs? Can I create a "root" page for my CPT with out the page path, and then have paths for other pages?

Say I have a CPT called I dunno, Library which is just a set of pages (has_archive = false) and the rewrite slug is library. I also intend to have a set of pages like about, archive, and new books.

Can I do something so that I make a page called home and instead of its url being https://example.org/library/home could it be https://example.org/library? And then the about page would have the url of https://example.com/library/about

NOTE - I know that I could set the rewrite slug to / and then create a new page named library and then make things like the about or archive pages children of library but I feel like is just an extra step my users are going to be unhappy about having to do.

And if I made a second CPT, library-books would there be away to set its rewrite slug to library/books or would I need a totally different path? so I would want https://example.org/library/books to be the archive for the library-books CPT and then https://example.org/library/books/book-title for the individual book posts.

Topic paths rewrite-rules permalinks custom-post-types Wordpress

Category Web


The way I see it, you could do:

// Via the init hook, do all these:

register_post_type( 'library-books', [
    'public'      => true,
    'label'       => 'Library Books',
    'rewrite'     => [ 'with_front' => false, 'slug' => 'library/books' ],
    'has_archive' => 'library/books',
    // other args here
] );

register_post_type( 'library', [
    'public'      => true,
    'label'       => 'Libraries',
    'rewrite'     => [ 'with_front' => false, 'slug' => 'library' ],
    'has_archive' => false,
    // other args here
] );

add_rewrite_rule( '^library/?$', 'index.php?library=home', 'top' );

I.e.

  • Register the library-books CPT first, with library/books as the rewrite slug as well as has_archive.

  • Then register the library CPT with library as the rewrite slug, and has_archive set to false.

  • And register a custom rewrite rule for the example.com/library which (internally) loads example.com/library/home (which is a post of the library CPT, although you can really modify the rewrite rule's query to load a post of a different post type such as page).

But of course, in your library CPT, you shouldn't have a post with books as the slug.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.