Removing the Slug in a Custom Post Type Permalink

For a long time, having a slugless permalink aka a postname permalink was a luxury feature that only posts and pages in WordPress shared. Though the performance issues that plagued using the postname permalink was resolved with WordPress 3.3, it was still sort of tricky to implement it. I found a few tutorials online but I decided to find my own way of doing it.

The tough part to figure out. You notice that if you only did parts one and two, WordPress would give your new post type links but the links would 404. The reason? WP doesn’t know what post type to query for when it is given only a post name, like our permalink would resolve to. When all else fails, it’ll default to post and with that, won’t find our custom post.

The solution uses the parse_query action to check all queries for two conditions: whether a name is being queried (ie name is not empty) and whether a post_type is set. If there is a name but not a post_type, the function will set post_type as post, page and our custom post type. Refresh your permalinks and the link should now work!

The only issue found with this is (thanks to Simon Blackbourn of wp-hackers) that if you happen to have a post or page of the same name, both will occupy the same page. Trashed posts of the same name will cause 404 errors until you delete it.

If you’ve found any flaws to my technique, please let me know. Feedback is appreciated!

3 thoughts on “Removing the Slug in a Custom Post Type Permalink”

Sorry, didn’t quite debug this thoroughly enough. Forgot to add a bit of code. The Gist now has the complete example and should be more or less bug free. Let me know if you run into any more problems: https://gist.github.com/funkedgeek/9233561