Remove Slug from Custom Post Type results in 404

The registering of the custom post type and the permalink modification is OK. The problem is with the WordPress rewrite rules that more than likely will match the “cleaned up” URL of your simple links to pages and it will set the pagename query var not name as your change_slug_struct() function assumed.

So change the function to this to account for all cases:

function change_slug_struct( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }

    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'post', 'single-link', 'page' ) );
    } elseif ( ! empty( $query->query['pagename'] ) && false === strpos( $query->query['pagename'], "https://wordpress.stackexchange.com/" ) ) {
        $query->set( 'post_type', array( 'post', 'single-link', 'page' ) );

        // We also need to set the name query var since redirect_guess_404_permalink() relies on it.
        $query->set( 'name', $query->query['pagename'] );
    }
}
add_action( 'pre_get_posts', 'change_slug_struct' );

Leave a Comment