Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielmcclure/baf3d72359e68deeb8c5ed5d23542b19 to your computer and use it in GitHub Desktop.
Save danielmcclure/baf3d72359e68deeb8c5ed5d23542b19 to your computer and use it in GitHub Desktop.
Remove custom post type slug from permalinks in WordPress
<?php
// Safely Remove CPT slugs from your CPT permalinks.
// Note: Replace CPT_NAME with your CPT name.
/**
* Remove the slug from published post permalinks. Only affect our custom post type, though.
*/
function m3_remove_cpt_slug( $post_link, $post ) {
if ( 'CPT_NAME' === $post->post_type && 'publish' === $post->post_status ) {
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'm3_remove_cpt_slug', 10, 2 );
/**
* Have WordPress match postname to any of our public post types (post, page, CPT_NAME).
* All of our public post types can have /post-name/ as the slug, so they need to be unique across all posts.
* By default, WordPress only accounts for posts and pages where the slug is /post-name/.
*
* @param $query The current query.
*/
function m3_add_cpt_post_names_to_main_query( $query ) {
// Bail if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Bail if this query doesn't match our very specific rewrite rule.
if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
return;
}
// Bail if we're not querying based on the post name.
if ( empty( $query->query['name'] ) ) {
return;
}
// Add CPT to the list of post types WP will include when it queries based on the post name.
$query->set( 'post_type', array( 'post', 'page', 'CPT_NAME' ) );
}
add_action( 'pre_get_posts', 'm3_add_cpt_post_names_to_main_query' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment