I recently updated the permalink structure of a website from /%postname%/
to /%category%/%postname%/
this is obviously causing 404 errors. Instead of writing 301 redirects for each post is there any way to do this in a more automated fashion, within WordPress? I essentially want to programmatically 301 redirect the URIs from the old permalink structure to the new one.
-
Not sure what is actually the question. If there are plugins that let you redirect URLs then all you have to do is find away to automatically populate them.– Mark KaplunCommented Feb 28, 2014 at 14:55
-
Also not sure what you asking. I cannot replicate your problem.– Pieter GoosenCommented Feb 28, 2014 at 14:57
-
I updated the permanent structure to include the category. Now the old URLs 404. Is there a way to programmatically 301 redirect the old permalink structure to the new one?– Zach RussellCommented Feb 28, 2014 at 15:00
-
I updated the question to make it a little more clear if it wasn't before @MarkKaplun– Zach RussellCommented Feb 28, 2014 at 16:04
3 Answers
You can make a catch on 404 in wordpress with filter 404_template
Or you can use redirection plugin: http://wordpress.org/plugins/redirection/screenshots/ with Regex.
Can you follow the link in this Question: Catch 404 after changing permalink structure from /%postname%/ to /%category%/%postname%/
/**
* Redirect a "/%postname%/" permalink structure to the their new URL.
*
* @link http://wordpress.stackexchange.com/q/136306/1685
*/
function wpse_136306_redirect() {
global $wp;
// Check that we've hit a 404 for a non-empty permalink without slashes
if ( is_404() && strlen( $wp->request ) && strpos( $wp->request, '/' ) === false ) {
// Attempt to find a post that matches the request.
$posts = get_posts(
array(
'posts_per_page' => 1,
'name' => $wp->request,
)
);
if ( $posts && $url = get_permalink( $posts[0]->ID ) ) {
// All good, let's redirect to the new URL.
wp_redirect( $url, 301 );
exit;
}
}
}
add_action( 'template_redirect', 'wpse_136306_redirect', 1 );
-
Thank you for your answer. Is there any advantages or disadvantages using this method versus the one in the above answer? I just want to make sure i'm implementing this in the best way possible @thedeadmedic Commented Feb 28, 2014 at 16:27
-
If you are OK with a Wordpress plugin , you can use the WP redirection plugin.
Regular expressions are your friends https://redirection.me/support/redirect-regular-expressions/
In the Source URL
, set .*
In Target URL
, set /category/$1
. The tricky part is your category
is a variable.