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!!

Advertisements

Sr. Software Engineer

Tagged with: , ,
Posted in Wordpress

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: