Today in this tutorial we are going to see how to remove slug from custom post type in WordPress without plugin.
I have been trying to remove the slug from custom post type because i want my slug to be shorter.There is a old fashioned way of removing the slug in custom type of WordPress by using the following code.
Take a look at it, now it no longer works in most recent versions of WordPress after 3.5
installs.
1 |
'rewrite' => array( 'slug' => true, 'with_front' => true), |
Change above line to
1 |
'rewrite' => array( 'slug' => false, 'with_front' => false), |
But now, it wont work adding only these piece of code in functions.php file because, we have to keep in mind that it will bring conflict if slug of custom post type and page or post may become same.
So what we will do is first remove the slug from the permalink by adding this single piece of code in functions.php.
1 2 3 4 5 6 7 8 9 10 11 |
function remove_cpt_slug( $post_link, $post, $leavename ) { if ( 'your-cpt-slug' != $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', 'remove_cpt_slug', 10, 3 ); |
And now if you visit the page you will get Page Not Found Error
because its not enough.
Why ?
Because WordPress behave only post and page to work this way.
To make it work we need to add certain line of codes to tell WordPress to behave custom post type as page or post. To do this add these lines of codes in functions.php to make it work for custom post type as well.
1 2 3 4 5 6 7 8 9 10 11 |
function change_slug_struct( $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', 'your-cpt-slug', 'page' ) ); } } add_action( 'pre_get_posts', 'change_slug_struct' ); |
Now go to Settings -> Permalinks
and save changes without making any other changes in the permalinks section and you are good to go. Check your custom post type posts your slug have been removed from custom post type permalink structure.
If you have any other problem you can contact us via contact form from the contact us page. We will be happy to sort it out.
Leave a Reply