prettyboymp的答案与我昨天得到的答案几乎相同,但我对此不满意。prettyboymp的回答有一个缺陷,当同时在多种帖子类型上使用/%postname%/时,它不起作用。
这是我的答案,该答案也针对当前结构,并创建了一系列后备类型。但是,如果两个帖子类型都具有相同的标记并且都为/%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"));