Skip to content

Instantly share code, notes, and snippets.

@Garconis
Last active July 3, 2019 16:50
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 Garconis/fa98d6824750beddcf6a90a29b551b5a to your computer and use it in GitHub Desktop.
Save Garconis/fa98d6824750beddcf6a90a29b551b5a to your computer and use it in GitHub Desktop.
WordPress | Hack to get CPT to have no post-type slug
<?php
/**
* NOTE, this causes PAGES AND POSTS TO NOT WORK!
*/
/**
* NOTE, this also requires your post type (e.g., via CPT UI) to have a Rewrite to True,
* and a Custom Rewrite Slug of / (forward slash) ... which probably isn't best practice.
* Sources:
* https://kellenmace.com/remove-custom-post-type-slug-from-permalinks/
* https://wordpress.stackexchange.com/a/282040/91826
* https://wordpress.org/support/topic/cpt-without-any-front-slug-at-all/
* https://core.trac.wordpress.org/ticket/34136
*/
/**
* Have WordPress match postname to any of our public post types (post, page, race).
* 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/.
*/
function gc_add_cpt_post_names_to_main_query( $query ) {
// Bail if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Bail if this query doesn't match our very specific rewrite rule.
if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
return;
}
// Bail if we're not querying based on the post name.
if ( 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', 'fs_local' ) );
}
add_action( 'pre_get_posts', 'gc_add_cpt_post_names_to_main_query' );
/**
* Force check the slug of the custom post type, and also the posts and page.
* Compare them and make sure they aren't a duplicate slug from the other post type.
*/
function gc_prevent_slug_duplicates( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
$check_post_types = array(
'post',
'page',
'fs_local'
);
if ( ! in_array( $post_type, $check_post_types ) ) {
return $slug;
}
if ( 'fs_local' == $post_type ) {
// Saving a fs_local post, check for duplicates in POST or PAGE post types
$post_match = get_page_by_path( $slug, 'OBJECT', 'post' );
$page_match = get_page_by_path( $slug, 'OBJECT', 'page' );
if ( $post_match || $page_match ) {
$slug .= '-duplicate';
}
} else {
// Saving a POST or PAGE, check for duplicates in fs_local post type
$fs_local_match = get_page_by_path( $slug, 'OBJECT', 'fs_local' );
if ( $fs_local_match ) {
$slug .= '-duplicate';
}
}
return $slug;
}
add_filter( 'wp_unique_post_slug', 'gc_prevent_slug_duplicates', 10, 6 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment