prettyboymp的答案和我昨天得到的几乎一样,但我不满意。prettyboymp的答案有一个缺陷,即当/%postname%/同时用于多个帖子类型时,它不起作用。
这是我的答案,它也查看了当前的结构,并创建了一系列可以回退的帖子类型。不过,这也有一个缺陷,如果两个帖子类型具有相同的slug,并且都是/%postname%/那么它会同时显示这两个。
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"));