Remove base slug in CPT & CT, use CT in permalink

I copied your code as-is above, pasted it into the twentysixteen theme, and changed just the post type rewrite slug from review/%brand% to %brand%. This resulted in both the term archive and review posts having your desired URL structure and successfully displaying.

Now the bad news is that the rewrite rules generated for the taxonomy and post type stomp all over the post and page rewrite rules. A request for a post results in WordPress trying to find a brand term matching your post slug. A request for parent-page/child-page results in WordPress trying to query a review post matching child-page.

The good news is that we can fix this. When a request is parsed by WordPress, all of the potentially matching query vars are populated, and are passed through the request filter where we can modify and transform them.

To peek into this filter, try:

function test_request( $request ){
    echo '<pre>';
    print_r($request);
    echo '</pre>';
}
add_filter( 'request', 'test_request' );

Then visit different types of pages and see what query vars get populated.

I hacked together a quick example that fixes basic post and child page display. This doesn’t cover everything that might be broken. I haven’t tested paginated posts, attachments, other stuff?? This also may change if you’ve got other post types, or your post permalink structure changes. But this should give you a starting point for getting things working.

function wpd_fix_requests( $request ){

    // if it's a brand term request
    // see if a brand term exists by this name with get_term_by
    // if not, reset the query to a post or page with name
    if( array_key_exists( 'brand' , $request )
        && ! array_key_exists( 'post_type' , $request )
        && ! get_term_by( 'slug', $request['brand'], 'brand' ) ){
            $request['name'] = $request['brand'];
            $request['post_type'] = array( 'post', 'page' );
            unset( $request['brand'] );
    }

    // if this is a review request
    // add page to post type in case it's a child page
    if( array_key_exists( 'review', $request ) ){
        $request['post_type'] = array( 'review', 'page' );
    }

    // return request vars
    return $request;
}
add_filter( 'request', 'wpd_fix_requests' );

Leave a Comment