Changed permalink structure – old links no longer work
-
The easiest way for me to explain my problem is to create a guide on how to reproduce it. See below.
My question is: How do I add a rewrite rule to WordPress so that old URLs still work after updating the permalink structure?
Install WP & Update Permalinks
Go to Settings > Permalinks.
Select “Day and name” which displays format:/%year%/%monthnum%/%day%/%postname%/
Save.Create a post for testing
Create a post called “Test”.
Permalink structure should be of format:/2015/09/21/test/
before publishing.
Publish.
Click “View post”.
Save URL.Add actions/filters
Add this to functions.php:function main_theme() { add_rewrite_tag('%MAIN_THEME%', '([^&/]+)'); register_taxonomy( 'main_theme', array('post'), array( 'label' => 'Main Theme', 'hierarchical' => true, ) ); } add_action('init', 'main_theme');
and
function main_theme_post_link($post_link, $post) { if (!empty($post) && $post->post_type == 'post') { $terms = wp_get_object_terms($post->ID, 'main_theme'); if ($terms) { $theme = $terms[0]->slug; return str_replace('%MAIN_THEME%', $theme, $post_link); } } return $post_link; } add_filter('post_link', 'main_theme_post_link', 1, 3); add_filter('post_type_link', 'main_theme_post_link', 1, 3);
Create category
Click on “Main Theme” located under “Posts”.
Create a new category called “Fruits”.Update Permalinks
Go to Settings > Permalinks.
Select custom format:/%MAIN_THEME%/%postname%/
Save.Create another post for testing
Create a post called “Test2”.
Permalink structure should be of format:/%MAIN_THEME%/test2/
before publishing.
Select “Fruits” from “Main Theme” in sidebar.
Publish.
Permalink should be updated and say:/fruits/test2/
Final test
Go to 2nd post by opening URL:/fruits/test2/
“Test2” should load correctly.Problem!!
Now load 1st post by opening URL:/2015/09/21/test/
Page is redirected to URL:/%MAIN_THEME%/test/
and “Bad Request” is displayed.How do I force WP to support old permalink structure as well as new structure?
I have tried adding the following to above init hooks without success:
add_rewrite_rule('^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*)$', 'index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&pagename=$matches[4]', 'top');
- The topic ‘Changed permalink structure – old links no longer work’ is closed to new replies.