我使用了名为Dreamland的wordpress主题,它已经取消了一些自定义帖子类型和分类法。我想更改永久链接结构,以便在url中省略slug。我发现的几乎所有解决方案都基于register_post_type()函数的重写参数。我试图在注册自定义帖子类型的地方直接更改它,或者通过register_post_type_args过滤器,如下所示:
function custom_post_type_args( $args, $post_type ) {
if ( $post_type == "bunch_property" ) {
$args['rewrite'] = array(
'slug' => ''
);
}
return $args;
}
add_filter( 'register_post_type_args', 'custom_post_type_args', 999, 2 );
始终以404错误结束。重要的信息是,只有允许的slu is是" property"虽然这个帖子类型的真实slu is是" bunch_property"。我的分类法称为" property_category"但是我通过this solution解决了它。对于帖子类型而不是分类法,还有类似的东西吗?或者除了.htaccess上的重写规则之外的任何其他解决方案?
答案 0 :(得分:1)
尝试此解决方案Remove Custom Post Type Slug from Permalinks
function gp_remove_cpt_slug($ post_link,$ post,$ leavename){
if ( 'bunch_property' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'gp_remove_cpt_slug', 10, 3 );
function gp_parse_request_trick( $query ) {
// Only noop the main query
if ( ! $query->is_main_query() )
return;
// Only noop our very specific rewrite rule match
if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
// 'name' will be set if post permalinks are just post_name, otherwise the page rule will match
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'post', 'page', 'bunch_property' ) );
}
}
add_action( 'pre_get_posts', 'gp_parse_request_trick' );
将自定义分类添加到帖子类型网址
add_filter('generate_rewrite_rules', 'taxonomy_slug_rewrite');
function taxonomy_slug_rewrite($wp_rewrite) {
$rules = array();
// change "^property/([^/]+)/([^/]+)/?" to "^([^/]+)/([^/]+)/?" to test without "property" in url
$rules["^property/([^/]+)/([^/]+)/?"] = 'index.php?post_type=bunch_property&property_category=$matches[1]&resource=$matches[2]';
// merge with global rules
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
答案 1 :(得分:0)
最后,由于Sofiane Achouba,我解决了这个问题。除了add_rewrite_rule解决的最后一部分。它不是最优的,因为我必须调用循环来遍历所有帖子并为每个帖子应用add_rewrite_rule()函数:
function my_custom_rewrite() {
$args = array("post_type" => "bunch_property","posts_per_page" => -1);
$posts = get_posts( $args );
foreach($posts as $post){
$cat = get_the_terms($post,"property_category");
$cat_slug = $cat[0]->slug;
$post_slug = $post->post_name;
add_rewrite_rule('^'.$cat_slug.'/'.$post_slug.'?/','index.php/property/'.$cat_slug.'/'.$post_slug.'/', 'top');
}
}
add_action('init', 'my_custom_rewrite');
我已经尝试过只进行过类似的事情,但它不起作用。
这很奇怪,但这有效:
add_rewrite_rule('^xxx/(.*?)/', 'index.php/property/xxx/yyy/','top'); // where xxx is post name and yyy category slug
但是这样做了:
add_rewrite_rule('^xxx/(.*?)/', 'index.php/property/xxx/$matches/','top');
这让我得到了上面的解决方案。再说一遍,它不是最佳的。