Last active
October 26, 2018 23:30
-
-
Save feedmeastraycat/8046727 to your computer and use it in GitHub Desktop.
An experimental way to register a CPT where you can have just /%postname%/ rewrite without a prefixed slug. Not fully tested so let me know if something doesn't work. I've wanted to do this from time to time but never really found a good way to do it without some issues.
This file contains hidden or 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 | |
/* | |
Plugin Name: CPT Without Slug | |
Description: A test plugin to register a CPT without slug | |
Author: David Mårtensson | |
Version: 0.0.4 | |
Author URI: http://feedmeastraycat.net/ | |
*/ | |
add_action( 'init', 'mycpt_init' ); | |
function mycpt_init() { | |
register_post_type( 'mycpt', array( | |
'public' => true, | |
'rewrite' => array( 'with_front' => false, 'slug' => '/' ) | |
) ); | |
} | |
add_action( 'mycpt_rewrite_rules', 'mycpt_remove_rewrite_rules', 10, 1 ); | |
function mycpt_remove_rewrite_rules( $default_rules ) { | |
return array(); | |
} | |
add_action( 'pre_get_posts', 'mycpt_pre_get_posts', 11, 1 ); // Should prob run last | |
function mycpt_pre_get_posts( &$wp_query ) { | |
if ( !is_admin() && isset($wp_query->query_vars['name']) && !empty($wp_query->query_vars['name']) ) { | |
$wp_query->set( 'post_type', array( 'post', 'mycpt' ) ); | |
} | |
} |
Another issue which is related to the one above.
If you have a post type page, a post type post and a post type "mycpt", all three with the slug /hello-world/, the post type page will be shown. If the page is moved to the trash a 404 will be displayed. If the trash is emptied it will show as my previous comment.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Issue: Post name isn't unique so if you have /hello-world/ which is both a post type "post" as well as custom post type "mycpt" both will be in the loop. Even though is_single() is true and single.php is used. Which might be ok. But if you move the last created one to the trash can you will get a 404 page until the trash has been emptied.
Possible solution: Use wp_unique_post_slug_is_bad_flat_slug to make sure post type "post" and custom post type "mycpt" can't use the same post names.