Rewrite rule for changing permalinks. Post name to permalink with Category


SCENARIO A

  1. I have an wordpress site that has existing posts.

  2. Permalink structure is currently configured to https://sitename.com/%postname%/

  3. I need to change the Permalink structure to https://sitename.com/%category%/%year%/%monthnum%/%day%/%postname%/ but when I save these settings https://sitename.com/%postname%/ results to 404 does not redirect to https://sitename.com/%category%/%year%/%monthnum%/%day%/%postname%/

  4. When I remove the /%category%/ and just use https://sitename.com/%year%/%monthnum%/%day%/%postname%/ the 301 redirection from https://sitename.com/%postname%/ works fine

Is there a better way to achieve changing to https://sitename.com/%category%/%year%/%monthnum%/%day%/%postname%/ with proper redirections from https://sitename.com/%postname%/?

Note: I already deactivate all plugins and just used the default twentytwenty theme. I have 11,000 existing posts.

SCENARIO B (if Scenario A does not work or there is no solution to Scenario A. Im looking at option Scenario B)

  1. The existing posts are under a category called "Local News", "local-news"
  2. Is there a way where I can just filter the rewrite rule so that if a post is under "Local News" category then the permalink structure will be https://sitename.com/%postname%/ then all other new posts will follow the main permalink structure I have set which is https://sitename.com/%category%/%year%/%monthnum%/%day%/%postname%/ ?

Currently I have this but I’m not sure it’s working properly. When I apply this it seems to work for posts that are under "Local News" category. However it breaks my PAGES. PAGES result in 404s.

function custom_permalink( $  permalink, $  post, $  leavename ) {     // Get the category for the post     $  category = get_the_category($  post->ID);     if (  !empty($  category) && $  category[0]->cat_name == "Local News" ) {         $  cat_name = strtolower($  category[0]->cat_name);         $  permalink = trailingslashit( home_url('/' . $  post->post_name .'/' ) );     }     return $  permalink; }  add_action( 'init', 'custom_rewrite_rules' ); function custom_rewrite_rules() {     add_rewrite_rule(         '([^/]+)(?:/([0-9]+))?/?$  ',         'index.php?category_name=local%news&name=$  matches[1]&page=$  matches[2]',         'top' // The rule position; either 'top' or 'bottom' (default).     ); } 

Is this a correct approach or is my code correct? I’m also not sure if the rewrite rules I made affects other things. Basically I just want to retain permalink/url of the old posts and moving forward I want to follow the new permalink settings. I’m avoiding old posts to result in 404 pages.

Thanks