Adding two rewrite rules

时间:2016-06-08 作者:Marcos Rezende

我有一个带有自定义分类法的自定义帖子类型。

自定义帖子类型为新闻。

自定义分类是new\\u category。

我想要的是两个操作链接的可能性:

http://example.com/news/ -> show news archive
http://example.com/news/movies/ -> show category movie archive
http://example.com/batman-returns/ -> show post content called "Batman Returns"
我试过这个,但不起作用:

add_rewrite_rule(\'^news/([^/]*)/?\',\'index.php?post_type=news&news=$matches[1]\',\'top\');
add_rewrite_rule(\'^news/([^/]*)/?\',\'index.php?post_type=news&news_category=$matches[1]\',\'top\');
建议?

1 个回复
最合适的回答,由SO网友:dan9vu 整理而成

1. Change new_category taxonomy\'s rewrite rule while registering:

\'rewrite\' => [\'hierarchical\' => false, \'with_front\' => false, \'slug\' => \'news\']
确保重写规则news post type为默认值或:

\'rewrite\'  => [\'slug\' => false, \'with_front\' => false]
2. Add rewrite rules for new_category:

add_action(\'init\', function()
{
    add_rewrite_rule(\'^news/([^/]+)/?$\', \'index.php?new_category=$matches[1]&post_type=news\', \'top\');
});
3. Filter news post type links:

add_filter(\'post_type_link\', function($post_link, $post, $leave_name = false, $sample = false)
{
    if ( \'news\' === $post->post_type)
    {
        $post_link = str_replace(\'/news/\', \'/\', $post_link);
    }

    return $post_link;

}, 10, 4);
4. Add news post type to query vars:

通过删除news WordPress将从permalink查询帖子post 发布类型,您将得到404 not found now。所以我们需要添加news 将类型过帐到查询变量。

add_action(\'pre_get_posts\', function($query)
{
    if ( $query->is_main_query() && ( 2 === count($query->query) ) && isset($query->query[\'name\']) )
    {
        $query->set(\'post_type\', [\'post\', \'news\', \'page\']);
    }
});
仅此而已。刷新permalink结构并确保其设置为/%postname%/.

相关推荐