您需要显示给定类型的帖子({post_type}) 来自类别({term})链接的结构应如下所示:
{post\\u type}/类别/{term}
为避免与页面链接和“博客”帖子发生冲突,表达式不能以开头([^/]+)
, 但应包含显式输入的post类型的slug。这意味着每个自定义帖子类型都有一个单独的规则。
$regex = \'^news/category/(.+?)/?$\';
对于上述表达式
$redirect
应包含
category_name
和
post_type
参数:
$redirect = \'index.php?category_name=$matches[1]&post_type=news\';
如果是自定义分类法(
^news/custom_tax_slug/(.+?)/?$
):
$redirect = \'index.php?CUSTOM_TAX_SLUG=$matches[1]&taxonomy=CUSTOM_TAX_SLUG&post_type=news\';
要处理分页,您需要另一个规则,它是上述规则的扩展版本。
$regex = \'^news/category/(.+?)/page/?([0-9]{1,})/?$\';
$redirect = \'index.php?category_name=$matches[1]&post_type=news&paged=$matches[2]\';
总之:
function category_cpt_rewrites()
{
add_rewrite_rule( \'^news/category/(.+?)/page/?([0-9]{1,})/?$\',
\'index.php?category_name=$matches[1]&post_type=news&paged=$matches[2]\',
\'top\'
);
add_rewrite_rule( \'^news/category/(.+?)/?$\',
\'index.php?category_name=$matches[1]&post_type=news\',
\'top\'
);
}
或:
function category_cpt_rewrites()
{
$post_types = [ \'news\' ];
foreach ( $post_types as $cpt )
{
add_rewrite_rule( \'^\'. $cpt .\'/category/(.+?)/page/?([0-9]{1,})/?$\',
\'index.php?category_name=$matches[1]&post_type=\'. $cpt .\'&paged=$matches[2]\',
\'top\'
);
add_rewrite_rule( \'^\'. $cpt .\'/category/(.+?)/?$\',
\'index.php?category_name=$matches[1]&post_type=\' . $cpt,
\'top\'
);
}
}