Remove custom post type slug from URL

That’s how you can do first part of the job – get rid o CPT slug in post link (eg. news post type).

function df_custom_post_type_link( $post_link, $id = 0 ) {  

    $post = get_post($id);  

    if ( is_wp_error($post) || 'news' != $post->post_type || empty($post->post_name) )  
        return $post_link;  

    return home_url(user_trailingslashit( "$post->post_name" ));  
}
add_filter( 'post_type_link', 'df_custom_post_type_link' , 10, 2 );

Now there should go a a rewrite rules for ‘news’, because you will get a 404 error.

Add the rewrite rule like this:

function df_custom_rewrite_rule() {
    add_rewrite_rule('(.*?)$', 'index.php?news=$matches[1]', 'top');
}
add_action('init', 'df_custom_rewrite_rule');

Then we’ll need to flush rewrite rules, so go to Settings – Permalinks and save changes.

Leave a Comment