Last active
October 7, 2022 01:27
-
-
Save wpexplorer/9745717 to your computer and use it in GitHub Desktop.
Remove Custom Post Type Slug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Remove the slug from published post permalinks for our custom post types. | |
*/ | |
add_filter( 'post_type_link', function( $post_link, $post, $leavename ) { | |
$post_types = array( | |
'post_type_1', | |
'post_type_2' | |
); | |
if ( in_array( $post->post_type, $post_types ) && 'publish' === $post->post_status ) { | |
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link ); | |
} | |
return $post_link; | |
}, 10, 3 ); | |
/** | |
* Some hackery to have WordPress match postname to any of our public post types. | |
* | |
* All of our public post types can have /post-name/ as the slug, so they better be unique across all posts | |
* Typically core only accounts for posts and pages where the slug is /post-name/ | |
*/ | |
add_action( 'pre_get_posts', function( $query ) { | |
// Only noop the main query. | |
if ( ! $query->is_main_query() ) | |
return; | |
} | |
// Only noop 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'] ) ) { | |
$post_types = array( | |
'post', // important to not break your standard posts | |
'page', // important to not break your standard pages | |
'post_type_1', | |
'post_type_2' | |
); | |
$query->set( 'post_type', $post_types ); | |
} | |
} ); |
@TopDMA - just add your types in an array and alter the code a bit. I updated the original gist since I'm sure most would like to affect multiple types.
If you need a plugin for adding post types to your site check out our Post Types Unlimited Plugin: https://wordpress.org/plugins/post-types-unlimited/
Thank You!!
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi i have 3 custom post type, and this code work only for one from them. How i can do this for all? Thank you