我有一个自定义永久链接结构,如下所示:
/%category%/%postname%/
类别库设置为.
,我有一些帖子类别,但想要为其中一个更改永久链接结构,名为Blog
。
所以我理解我需要为此类别下的帖子重写网址,并且我使用了这个:
add_filter('post_link', 'custom_permalink', 10, 3);
function custom_permalink ($permalink, $post, $leavename) {
// Get the categories for the post
$category = get_the_category($post->ID);
if (!empty($category) && $category[0]->cat_name == "Blog") {
$permalink = trailingslashit(home_url('/' . $post->post_name . '/'));
}
return $permalink;
}
因此,链接看起来没问题(URL中没有/blog/
),但结果是
错误404
现在我想我需要设置重写规则,尝试使用以下内容实现它:
add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules($wp_rewrite) {
// This rule will will match the post id in %postname%-%post_id% struture
$new_rules['^/([^/]+)/?$'] = 'index.php?name=$matches[1]';
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
return $wp_rewrite;
}
我认为我的重写规则不正确。你能告诉我它是如何修复的吗?
更新
我正在玩它并达到了这一点:
function custom_rewrite_rules($wp_rewrite) {
$new_rules['([^/]*)/?$'] = 'index.php?name=$matches[1]';
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
return $wp_rewrite;
}
现在所需的结构有效,但我得到Error
类别页面。这意味着这仍然是错误的([^/]*)/?$
。我如何才能将其限制为只有/
后的网址?
答案 0 :(得分:0)
答案 1 :(得分:0)
这可能是您正在寻找的内容:
function archive_rewrite_rules(){
add_rewrite_rule(
'blog/([^/]*)/?$',
'index.php?post_type=post&post_name=$matches[1]',
'top'
);
}
add_action( 'init', 'archive_rewrite_rules' );
将blog/
作为正则表达式的一部分应该将此重写规则限制为仅应用于博客类别。
永久链接设置可能会影响重写永久链接。