问题描述
有较早的帖子有类似的标题,但它不会看到 WordPress 3.3,这是重要的 3.3 广告有趣的是:「使用 postname 永久链接结构没有性能损失」
WordPress 3.2 及更早版本的问题是,首先它看起来是页面名称,然后是 404 。它没有首先检查任意的帖子类型。 3.3 另一方面,必须看后期类型,然后页面,最后 404(因为它通告这个功能) 。这意味着没有 slug 的自定义帖子类型应该是简单的,如果他们没有硬编码 post_type=post
在某个地方。
我找不到 3.3 具体的解决方案。
问题:如何为任何给定的自定义帖子类型”xyz” 定义永久链接结构”/%postname%/”?
谢谢。
最佳解决方案
这不容易在 WP 3.3 中完成,除非你将重写规则置于正确的位置,并使 wp_rewrite 认为在前端使用了详细规则。下面的课程是工作。
class Test_Post_Type {
const POST_TYPE = 'test';
public static function init() {
global $wp_rewrite;
$post_type_obj = register_post_type( self::POST_TYPE, array(
'labels' => array(
'name' => __( 'Tests' ),
'singular_name' => __( 'Test' ),
'add_new' => __( 'Add New' ),
'add_new_item' => __( 'Add New Test' ),
'edit_item' => __( 'Edit Test' ),
'new_item' => __( 'New Test' ),
'all_items' => __( 'All Tests' ),
'view_item' => __( 'View Test' ),
'search_items' => __( 'Search Tests' ),
'not_found' => __( 'No Tests found' ),
'not_found_in_trash' => __( 'No Tests found in Trash' ),
'menu_name' => __( 'Tests' )
),
'publicly_queryable' => true,
'exclude_from_search' => true,
'hierarchical' => false,
'public' => true,
'rewrite' => false,
'has_archive' => true,
'supports' => array( 'title', 'editor', 'thumbnail', 'test_source' ),
'taxonomies' => array( 'category', 'post_tag' ),
) );
$post_type_obj = get_post_type_object(self::POST_TYPE);
//register the rewrite tag for permalink building
$wp_rewrite->add_rewrite_tag( '%' . $post_type_obj->query_var . '%', '([^/]+)', $post_type_obj->query_var . '=' );
//we have to add the permastruct here in order to build the permalink, otherwise we'll need to filter the post_type link
add_permastruct(self::POST_TYPE, '%' . $post_type_obj->query_var . '%/', false );
//add a filter to remove the permastructs generated above
add_filter(self::POST_TYPE . '_rewrite_rules', array(__CLASS__, '_remove_default_rules'));
//now we add a filter to put the generated rewrite rules in the correct spot
add_action('generate_rewrite_rules', array(__CLASS__, '_filter_rewrite_rules'));
if(!is_admin()) {
//we need verbose_page_rules to be on on the front end in order for pages to be process properly
$wp_rewrite->use_verbose_page_rules = true;
}
}
/**
* Filter to remove the rules for this post type when they're automatically generated due to the permastruct registration
* @param type $rules
* @return type
*/
public static function _remove_default_rules($rules) {
return array();
}
/**
* Filters the rules at the end to add back the ones for this post type at the bottom
* @param WP_Rewrite $wp_rewrite
*/
public static function _filter_rewrite_rules($wp_rewrite) {
$post_type_obj = get_post_type_object(self::POST_TYPE);
$my_rules = $wp_rewrite->generate_rewrite_rules('%' . $post_type_obj->query_var . '%', EP_NONE);
$wp_rewrite->rules += $my_rules;
}
}
add_action( 'init', array( 'Test_Post_Type', 'init' ) );
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。