Search code examples
wordpressapachehttp-redirectdnsseo

Best Method to Mass Convert WordPress URLs to new URL structure?


I have a plan laid out to migrate my 30k+ posts WordPress site to a custom site built by me. One of the main contention points I have is SEO and I'm pretty sure I need to properly forward all of my post URLs if I don't want to decimate my SEO on Google (which is doing extremely well for me).

Current Structure: https://ygoprodeck.com/xyz-rank-up-shark/

New Structure: https://ygoprodeck.com/deck/xyz-rank-up-shark

This part is easy as I can build the new URLs using the post_name column from WordPress in the new Database and simply redirect the old URLs to the new /deck/ URLs. However, how can I make the forwarder differentiate between posts and pages?

Take this example:

Current Structure: https://ygoprodeck.com/ritual-summoning-the-underdogs-greatest-hits/

New Structure: https://ygoprodeck.com/article/ritual-summoning-the-underdogs-greatest-hits/

I'm not entirely sure how my forward will know to redirect to /deck/ or redirect to /article/ ?

The only solution I can think of is manually redirecting each 30k+ URL which seems like a monumental task to me.


Solution

  • Something like this:

    $file = wp_get_upload_dir() . 'rules.txt';
    $open = fopen( $file, "a" );
    
    args = array('post_type' => 'post', 'posts_per_page' => -1 );
    $posts = new WP_Query($args);
    
    if( $posts->have_posts() ){
        while( $posts->have_posts() ){
            $posts->the_post();
            global $post;
    
            $permalink = get_permalink($post->ID);
            //Assuming each post has only 1 category
            $category =  get_the_category($post->ID)[0]->name;
    
            $write = fputs( $open, 'Redirect 301 ' . $permalink . ' /' . $category . $permalink. '\n' );
        }
        flocse( $open );
        wp_reset_query();
    }