Rewrite rule for changing permalinks. Post name to permalink with Category
SCENARIO A
-
I have an wordpress site that has existing posts.
-
Permalink structure is currently configured to https://sitename.com/%postname%/
-
I need to change the Permalink structure to
https://sitename.com/%category%/%year%/%monthnum%/%day%/%postname%/
but when I save these settingshttps://sitename.com/%postname%/
results to 404 does not redirect tohttps://sitename.com/%category%/%year%/%monthnum%/%day%/%postname%/
-
When I remove the /%category%/ and just use
https://sitename.com/%year%/%monthnum%/%day%/%postname%/
the 301 redirection fromhttps://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)
- The existing posts are under a category called “Local News”, “local-news”
- 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 ishttps://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
Leave an answer
You must login or register to add a new answer .