Removing Slug from Custom Post Type in WordPress

While slugs are useful for organizing content and improving SEO, there are scenarios where removing the slug from a custom post type becomes desirable. One common reason is to create cleaner and more concise URLs, especially for custom post types that serve as landing pages or have shorter titles. Removing the slug can also enhance the aesthetics of your permalinks and make them more user-friendly.

1. Remove the slug from the permalink

Removing the slug from the permalink can be approached in two ways, depending on your specific situation. The first method involves modifying the parameters within the register_post_type() function. By adding the rewrite parameter. Alternatively, if you are unable to alter the parameters directly, the second method involves utilizing the post_type_link filter. This filter allows you to dynamically manipulate the permalink structure.

A. First method

function youbou_create_post_type() {

    $labels = array(
        'name'          => __( 'youbou CPT', 'youbou' ),
        'singular_name' => __( 'youbou CPT', 'youbou' ),
    );

    register_post_type( 'youbou_cpt',
        array(
            'labels'  => $labels,
            'public'  => true,
            'rewrite' => array(
                'slug'       => '/',
                'with_front' => false,
            ),
        )
    );
}
add_action( 'init', 'youbou_create_post_type' );

B. Second method

function youbou_remove_slug( $post_link, $post, $leavename ) {

    if ( 'youbou_cpt' != $post->post_type || 'publish' != $post->post_status ) {
        return $post_link;
    }

    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );

    return $post_link;
}
add_filter( 'post_type_link', 'youbou_remove_slug', 10, 3 );

While both of these methods effectively remove the slug from the permalink, it’s crucial to note that this change alone isn’t sufficient. Removing the slug can lead to a 404 error page when attempting to visit the new URL. To prevent this issue, it’s crucial to inform WordPress to treat our Custom Post Type in a manner similar to posts and pages.

2. Modifying Main Query to include our custom post type

This function extends WordPress’s query capabilities to include the specified custom post type when searching for content by name or slug, ensuring a seamless integration of the custom post type into the site’s content retrieval system.

function youbou_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', 'page', 'youbou_cpt' ) );
    }
}
add_action( 'pre_get_posts', 'youbou_parse_request' );

Note: Just remember, conflicts can occur easily if your custom post type shares the same name as a page or post.

#