Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Last active March 26, 2024 00:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kellenmace/38e3d26d1c2e50e8d64fe30605d16b59 to your computer and use it in GitHub Desktop.
Save kellenmace/38e3d26d1c2e50e8d64fe30605d16b59 to your computer and use it in GitHub Desktop.
Remove Slug from Custom Post Type URL in WordPress
<?php
/**
* Plugin Name: Remove Slug from Custom Post Type
* Description: Remove slug from custom post type URLs.
* Version: 0.1.0
* Author: Kellen Mace
* Author URI: https://kellenmace.com/
* License: GPLv2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
/**
* Remove the slug from published post permalinks. Only affect our custom post type, though.
*
* @param string $post_link The post permalink (URL).
* @param WP_Post $post The post object.
*
* @return string $post_link The post permalink (URL), possibly modified.
*/
function km_remove_cpt_slug( $post_link, $post ) {
if ( 'my-cpt-slug' === $post->post_type && 'publish' === $post->post_status ) {
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'km_remove_cpt_slug', 10, 2 );
/**
* Have WordPress match postname to any of our public post types (post, page, my-cpt-slug).
* 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 km_add_cpt_post_names_to_main_query( $query ) {
// Bail if this is not the main query, the query does not match our rewrite rule,
// or if we're not querying based on the post name.
if (
! $query->is_main_query()
|| ! isset( $query->query['page'] )
|| 2 !== count( $query->query )
|| 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', 'my-cpt-slug' ) );
}
add_action( 'pre_get_posts', 'km_add_cpt_post_names_to_main_query' );
@mhosseint
Copy link

Hello,
How do I remove the Slug related to the Brands post type from this code?

@kellenmace
Copy link
Author

@mhosseint You can follow the steps in this blog post to learn how:
https://kellenmace.com/blog/remove-custom-post-type-slug-from-permalinks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment