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



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

  2. Permalink structure is currently configured to

  3. I need to change the Permalink structure to but when I save these settings results to 404 does not redirect to

  4. When I remove the /%category%/ and just use the 301 redirection from works fine

Is there a better way to achieve changing to with proper redirections from

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

(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 then all other new posts will follow the main permalink structure I have set which is ?

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() {
        '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.


Marco 4 months 0 Answers 10 views 0

Leave an answer