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 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' ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.