WordPress   

Remove custom post type slug in WordPress

Now you can easily remove annoying custom post type slug from the single post URLs in WordPress by using this small code snippet. Don’t forget to replace “books” with the required custom post type before using this code snippet in your WordPress website.

Old URL

https://example.com/post_type_slug/single_post_slug

New URL

https://example.com/single_post_slug

Code Snippet

//Remove Custom post type slug
function remove_custom_post_slug( $postLink, $post ) {
	if ( 'books' === $post->post_type && 'publish' === $post->post_status ) {
		$postLink = str_replace( '/' . $post->post_type . '/', '/', $postLink );
	}
	return $postLink;
  }
  add_filter( 'post_type_link', 'remove_custom_post_slug', 10, 2 );
  
  function add_custom_post_types_to_main_query( $query ) {
	if ( ! $query->is_main_query() ) {
		return;
	}
	if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
		return;
	}
	if ( empty( $query->query['name'] ) ) {
		return;
	}
	$query->set( 'post_type', array( 'post', 'page', 'books' ) );
  }
  add_action( 'pre_get_posts', 'add_custom_post_types_to_main_query' );
Need Professional Support for Your Website Problems?

Whether you're facing website issues or struggling with code implementation, our team is here to assist. Hire us to get your website back on track.

Hire Us