How can i remove Custom Post Type Slug from WordPress URL?

*** First of all, don’t create the slug for your custom post type is the same as a page or post’s slug when you register a custom post type. Conflicts can happen if you do this.***

To remove Custom Post Type(CPT) Slug from the URL, First we need to add a filter function in post_type_link filter hook. In this function, we need to remove the post type slug for published posts from the $post_link parameter and return the modified $post_link variable. Here is the example below:

function wpartisan_remove_custom_post_type_slug( $post_permalink, $post ) {
    if ( 'quick-tips' === $post->post_type && 'publish' === $post->post_status ) {
        $post_permalink = str_replace( '/' . $post->post_type . '/', '/', $post_permalink );
    }
    return $post_link;
}
add_filter('post_type_link', 'wpartisan_remove_custom_post_type_slug', 10, 2);

Then we need to add a function in pre_get_posts action hook. Because by default WordPress only knows the URLs for Posts and Pages without the post type slug. So now, if we visit this Custom Post Type posts link, it will go to a 404 page. So we need to teach WordPress about our Custom Post Type URLs, so they behave like Posts and Pages URLs.

function wpartisan_parse_request( $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', 'quick-tips', 'page' ) );
    }
}
add_action( 'pre_get_posts', 'wpartisan_parse_request' );

Leave a Reply

Your email address will not be published. Required fields are marked *