Modify the permalink structure for a specific category

A user posted several correction ideas; unfortunately, they were deleted, but I managed to remember some things and apply them to the code. The 404 error no longer appears; now it generates the following:

Try deleting cookies.
ERR_TOO_MANY_REDIRECTS

add_filter('post_link', 'custom_permalink', 10, 3);
function custom_permalink($permalink, $post, $leavename) {
    $categories = get_the_category($post->ID);        
    $news_category = array_filter($categories, function ($category) {
        return $category->slug === 'news';
    });

    if (!empty($news_category)) {
        $post_date = get_the_date('Y/m/d', $post->ID);
        $permalink = home_url("/news/{$post_date}/{$post->post_name}/");
    }

    return $permalink;
}

add_action('init', 'custom_rewrite_rules');
function custom_rewrite_rules() {
    $rules = get_option('rewrite_rules', array());
    $regex = 'news/([0-9]{4})/([0-9]{2})/([0-9]{2})/([^/]*)/?$';
    add_rewrite_rule($regex, 'index.php?name=$matches[4]', 'top');

    if (!isset($rules[$regex])) {
        flush_rewrite_rules();
    }
}
add_action('template_redirect', 'custom_path_validation');

function custom_path_validation() {
    if (get_query_var('custom_path_redirected')) {
        return;
    }
    $request_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), "https://wordpress.stackexchange.com/");
    $news_regex = '^news/(\d{4})/(\d{2})/(\d{2})/([^/]+)/?$';

    if (preg_match("~$news_regex~", $request_path, $matches)) {
        $post_name = sanitize_title($matches[4]);
        $new_url = home_url("/news/{$matches[1]}/{$matches[2]}/{$matches[3]}/$post_name/");

        if ($request_path !== ltrim(parse_url($new_url, PHP_URL_PATH), "https://wordpress.stackexchange.com/")) {
            set_query_var('custom_path_redirected', true);
            wp_redirect($new_url, 301);
            exit;
        }
    }
}
add_action('template_redirect', 'custom_path_validation');

I’m trying to reach a solution, as soon as I achieve it, I’ll post it here. I believe it will help many users, as the solutions found so far are incomplete due to being outdated.

deneme bonusudeneme bonusu veren sitelerpulibet girişOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino