prettyboymp answer is almost the same I got yesterday, but I'm not happy with it. prettyboymp's answer has a one flaw, it does not work when /%postname%/ is being used simultaenously on multiple post types.
Here is my answer, which also looks in to current structure, and creates array of post types to fallback on. There is one flaw in this too though, if two post types have same slug and both are /%postname%/ then it shows both.
class MyCustomPostType {
/**
* Register post type
**/
public static function register_post_type() {
global $wp_rewrite;
$args = array(
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => false,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','thumbnail')
);
register_post_type('my_custom_post_type', $args);
// Enables the pages to work simultaneously
$wp_rewrite->use_verbose_page_rules = true;
add_filter("rewrite_rules_array", array(__CLASS__, 'rewrite_rules_array'));
add_action("parse_query", array(__CLASS__, 'parse_query'));
add_filter("post_type_link", array(__CLASS__, 'post_type_link'), 1, 4);
}
public static function post_type_link($link, $post, $leavename=false, $sample=false) {
if ($sample && ($begin = strpos($link, "?my_custom_post_type=")) !== false) {
return substr($link, 0, $begin-1) . "/%my_custom_post_type%/";
}
return str_replace("?my_custom_post_type=", "", $link) . "/";
}
public static function parse_query($query) {
global $wp, $wp_rewrite;
// Is this query for /%post_name%/? Is it main request query?
if (isset($query->query['name'])
&& substr($wp->matched_rule, 0, 7) == "([^/]+)"
&& isset($query->query)
&& isset($wp->query_vars)
&& $query->query == $wp->query_vars)
{
//echo '<p><h1>hit!</h1></p>';
if (!($post_types = get_query_var("post_type"))) {
if ($wp_rewrite->permalink_structure == "/%postname%/")
$post_types = array("post");
else
$post_types = array();
}
if (is_array($post_types))
$post_types[] = "my_custom_post_type";
set_query_var("post_type", $post_types);
//set_query_var("posts_per_page", 1);
}
}
public static function rewrite_rules_array($array) {
global $wp_rewrite;
// Same rules as in /%post_name%/
return array_merge($array, $wp_rewrite->generate_rewrite_rules("/%postname%/", EP_PERMALINK));
}
}
add_action('init', array("MyCustomPostType", "register_post_type"));