How remove custom post type slug from post url : wordpress

Hello Friends,
I you are using your own custom post type on wordpress site and want to remove the custom post type slug from post url then you can do it easily using hooks. You will no need to edit any wordpress core file, just copy and paste given blow code into your theme function.php file.

/** Start Removed custom post_type slug from posts url**/
function custom_parse_request_tricksy( $query ) {
    // Only noop the main query
    if ( ! $query->is_main_query() )
        return;
    // Only noop our very specific rewrite rule match
    if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }
    // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match
    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'project','post','page') );
    }
}
add_action( 'pre_get_posts', 'custom_parse_request_tricksy' );
 function custom_remove_cpt_slug( $post_link, $post, $leavename ) {
    if ( 'project' != $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', 'custom_remove_cpt_slug', 10, 3 );

We have given above example for “project” custom post type , you will need to update post type value as per your custom post type name.
 
Enjoy Code!!

2 Replies to “How remove custom post type slug from post url : wordpress”

  1. You ought to be a part of a contest for one of the greatest blogs on the web. I am going to recommend this website!

Leave a Reply

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