Skip to content

Instantly share code, notes, and snippets.

@groucho75
Last active August 29, 2015 14:21
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 groucho75/2bc76fa13a0961e786c9 to your computer and use it in GitHub Desktop.
Save groucho75/2bc76fa13a0961e786c9 to your computer and use it in GitHub Desktop.
WP: remove custom post type slug from post url and make unique post slugs among post types
/**
* Register your custom post type: write all the settings you like in $args.
*
* Note the 'slug' set to '/' to remove custom post type slug from url e.g.
* "/post-slug" instead of default "/custom-type-slug/post-slug"
*/
public function register_my_custom_type() {
$args = array(
/* ... */
'rewrite' => array('slug' => '/'),
/* ... */
);
register_post_type( 'custom_type', $args );
}
add_action( 'init', 'register_my_custom_type' );
/**
* Check a post slug against among all post types, instead of default WP that allow same slugs for different post types.
*
* Include this function as it is. The code is based on wp_unique_post_slug() core function, where the filter is applied.
*
* @see wp_unique_post_slug()
*
* @param $slug
* @param $post_ID
* @param $post_status
* @param $post_type
* @param $post_parent
* @param $original_slug
* @return string
*/
function make_unique_post_type_slug ($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug) {
global $wpdb, $wp_rewrite;
$feeds = $wp_rewrite->feeds;
if ( ! is_array( $feeds ) )
$feeds = array();
/*
* If a post and one of its attach has the same slug, be sure the rewrite of a post "beats" the attach rewrite.
* In this way, the original slug is assigned to the post.
* The attach has another slug automatically assigned: you can edit later editing the media screen.
*/
$not_attach = '';
if ( 'attachment' != $post_type ) {
$not_attach = " AND post_type != 'attachment' ";
}
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d {$not_attach} LIMIT 1";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $original_slug, $post_ID ) );
if ( $post_name_check || in_array( $original_slug, $feeds ) ) {
$suffix = 2;
do {
$alt_post_name = _truncate_post_slug( $original_slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
$suffix++;
} while ( $post_name_check );
$slug = $alt_post_name;
} else {
$slug = $original_slug;
}
return $slug;
}
add_filter( 'wp_unique_post_slug', 'make_unique_post_type_slug', 100, 6 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment