WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I made a site some time ago and after some days some posts were indexed by search engines. Today I changed the permalink structure from /%postname%/ to /%category%/%postname%/.

After that, when people come to my site from search engines a 404 page not found error appears. I want to change all old URLs to the new category base URL without any 404 error.

How can I do it?
By the way, I use Yoast plugin.

share|improve this question
Have you tried flushing your rewrite rules? – Manny Fleurmond Apr 5 '13 at 0:50

That happens because WordPress reads your old post name as category name now - and it cannot find that category.

Solution: filter 404_template and try to find the post and its permalink. Then redirect.

<?php  # -*- coding: utf-8 -*-
/* Plugin Name: Redirect to category */

add_filter( '404_template', 't5_redirect_to_category' );

function t5_redirect_to_category( $template )
    if ( ! is_404() )
        return $template;

    global $wp_rewrite, $wp_query;

    if ( '/%category%/%postname%/' !== $wp_rewrite->permalink_structure )
        return $template;

    if ( ! $post = get_page_by_path( $wp_query->query['category_name'], OBJECT, 'post' ) )
        return $template;

    $permalink = get_permalink( $post->ID );

    wp_redirect( $permalink, 301 );
share|improve this answer
Thank you for sharing this, it just saved me so much time writing 301 redirects! – Zach Russell Feb 28 '14 at 16:19
hi, where to add the above function? separate file? or inside functions.php? I am using genesis theme. – Jay Apr 27 '15 at 19:15
@Jay A separate plugin. This is why the code includes a plugin header. :) – toscho Apr 27 '15 at 22:12

You need to add 301 redirects from your old page urls to the new ones.

This plugin should accomplish what you want: http://wordpress.org/extend/plugins/redirection/

Because it detects changes to your permalinks and automatically adds redirects, you will need to switch back to your old permalink structure, activate the plugin, and then update your permalinks to the new structure.

Hope this helps.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.