Skip to content

Instantly share code, notes, and snippets.

@mattradford
Created October 15, 2014 22:32
Show Gist options
  • Save mattradford/74342b9ca6830ce0cb5c to your computer and use it in GitHub Desktop.
Save mattradford/74342b9ca6830ce0cb5c to your computer and use it in GitHub Desktop.
Remove slug from CPT
// Remove slug from CPT
// Careful of collisions and permalink must be %postname%
// http://www.itsabhik.com/remove-custom-post-type-slug/
// There was an error in the code after $args array: , not ;
// See also http://colorlabsproject.com/tutorials/remove-slugs-custom-post-type-url/
function remove_cpt_slug( $post_link, $post, $leavename ) {
$args = array(
'public' => true,
'_builtin' => false );
$cpts = get_post_types( $args, 'objects' );
foreach ( $cpts as $cpt ) {
//Replace the slug
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );
function include_cpt_query( $query ) {
// Only loop the main query
if ( ! $query->is_main_query() )
return;
// Only loop 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', get_post_types() );
}
}
add_action( 'pre_get_posts', 'include_cpt_query' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment