Ah! Great! A lucky guess.
Having two post types with a root rewrite rule gets a bit tricky, because Rewrites are basically an array of regexes —?the first regex to match the URL wins. So if two post types (pages and another) get registered with /
as the rewrite base, whichever is first will be chosen over the other.
Which rewrite matches can most easily be seen in the Debug This plugin menu: Debug This > Query > Rewrites
, the order of which can be edited with the rewrite_rules_array filter.
But that doesn’t solve the problem of two post types having the same rewrite path. For that, pre_get_posts
is a solution. In a case where both Pages and a Custom Post Type called “product” have a rewrite base of /
, I was able to get both to load with the following code:
add_action( 'pre_get_posts', function( $q ) {
if (
$q->is_main_query()
// If this installation is in a subdirectory,
// or a subdirectory multisite, then below [1] would be [2]
&& explode( '/', $_SERVER['REQUEST_URI'] )[1] === $q->query['name']
) {
$q->set(
'post_type',
[
// Post Types with rewrites set to '/' (root) directory
'page',
'product',
]
);
}
});
-
This reply was modified 3 years, 8 months ago by
Paul Clark.