如何在没有插件的情况下从特定类别的 post 的 URL 中删除日期?

How to remove the date from the URL of a post in a specific category, without plugin?

我需要一些帮助来找到仅从特定类别的 post 中删除 url 日期的解决方案。

我的永久链接设置如下:

 /%year%/%monthnum%/%day%/%category%/%postname%/

类别 x post 具有以下 url:

http://mysite/2021/08/25/category-x/post-name/

我只需要 category-x posts,url 看起来像这样:

http://mysite/category-x/post-name/

其他 post 将保留 url 中的日期。

我尝试使用 rewrite_rules_array 和 post_link 过滤器做一些事情,但没有成功。

我该如何解决?

更改类别基本前缀

更改类别基本前缀后尝试重定向

我是这样解决的:

add_filter( 'post_link', function( $permalink, $post, $leavename ){
    $category = get_the_category($post->ID);    
    if (  !empty($category) && $category[0]->slug == "category-x" ) {
        $permalink = trailingslashit( home_url('/category-x/'. $post->post_name . '/' ) );
    }
    return $permalink;
}, 10, 3 ); 

add_action('generate_rewrite_rules',function( $wp_rewrite ) {
    $new_rules['^category-x/([^/]+)/?$'] = 'index.php?name=$matches[1]';
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite;
});

还是谢谢你!