2
votes

My question is similar to Wordpress (Postname Permalink) 404 error however it goes beyond the question.

I have a client who has hundreds of pages in the default Wordpress blog structure YYYY/MM/post-name

and they want to move it to Permalink Structure /post-name

However the existing links in Google and other search engines must redirect to the correct 'new' page, not a 404, nor the home page.

My question is, with the latest version of Wordpress (at time of writing this 4.6.1) - if you simply go into SETTINGS>Permalinks>Post-Name will it work correctly?

OR

Do you still need to modify the .htaccess file so that the 'old page' redirects to the new page?

If so - what is the correct .htaccess file syntax so that each new link is a '301 redirect' telling the search engine that the page has moved permanently?

Thank you!

see also Wordpress Codex on Permalink Structure

3

3 Answers

2
votes

Use this template as alternative in your functions.php

add_action('template_redirect','check404');
function check404(){

     if (is_404() ) {

        $url = $_SERVER['REQUEST_URI'];
        $url = esc_url_raw( $url );

        //FIND IF THERE IS A POST...
        $e = explode("/", $url);

        $reversed = array_reverse($e);
        $number = $reversed[0];

        $link = get_permalink($number);
        if(!empty($link)){
            wp_redirect( $link, 301 );
            exit;
        }
        else
            return;
     }

}

This will redirect the /YYYY/MM/post-name/ -> /post-name/

1
votes

You can try this in your .htaccess

RewriteEngine On
Redirect 301 /YYYY/MM/post-name/ http://yoursite.com/post-name/

And you can create a file called enumerate.php to list all your posts:

include "wp-load.php";

$posts = new WP_Query('post_type=any&posts_per_page=-1&post_status=publish');
$posts = $posts->posts;

header('Content-type:text/plain');
foreach($posts as $post) {
    switch ($post->post_type) {
        case 'revision':
        case 'nav_menu_item':
            break;
        case 'page':
            $permalink = get_page_link($post->ID);
            break;
        case 'post':
            $permalink = get_permalink($post->ID);
            break;
        case 'attachment':
            $permalink = get_attachment_link($post->ID);
            break;
        default:
            $permalink = get_post_permalink($post->ID);
            break;
    }
    echo "\n{$permalink}";
    //echo "\n{$post->post_type}\t{$permalink}\t{$post->post_title}";
}

Put enumerate to the WordPress main folder and you will get the list that you can use for the .htaccess file.

1
votes

Lastly, you can just try to update the permalink structure :), and try the old URL.

If somethings goes wrong, you can revert to the old permalink structure.