Remove the Post Type Slug From URLs
Gives a custom post type short URLs like example.com/web-design/ instead of example.com/services/web-design/, as pages have.
Opens WPIDE on
Code
// Post type and its current slug.
$wpide_short_urls = array(
'post_type' => 'service',
'slug' => 'services',
);
add_filter( 'post_type_link', function ( $link, $post ) use ( $wpide_short_urls ) {
if ( $wpide_short_urls['post_type'] === $post->post_type && 'publish' === $post->post_status ) {
$link = str_replace( '/' . trim( $wpide_short_urls['slug'], '/' ) . '/', '/', $link );
}
return $link;
}, 10, 2 );
add_action( 'pre_get_posts', function ( $query ) use ( $wpide_short_urls ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
// A plain /name/ request is parsed as a post name: also look for it in the custom post type.
$vars = $query->query;
unset( $vars['page'] );
if ( 1 === count( $vars ) && ! empty( $vars['name'] ) ) {
$query->set( 'post_type', array( 'post', 'page', $wpide_short_urls['post_type'] ) );
}
} );
Notes
Needs the "Post name" permalink setting and a non-hierarchical post type. Avoid items with the same slug as a page or post.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.