I recently needed to change the structure of my urls in WordPress, the link was set to be at the root of my site and I needed the new format to have the category. The permanent link structure was /%postname%/ and now in the new format it would be /%category%/%postman%/ . A practical example:

  • Old link: https://marquesfernandes.com/o-que-e-python-e-pra-que-serve/
  • New link: https://marquesfernandes.com/desenvolvimento/o-que-e-python-e-pra-que-serve/

If you just change the structure and don't redirect, all old links will go to a 404 Error – Page Not Found page. So how to make this change without breaking the links already created and indexed in Google?

What we need to do is try to capture the URL that would cause the 404 error and try to find the post's new permanent link. If no links are found, then we will display the not found page. The method is quite simple, as long as your old URL has something that we can use to search for the new link, such as the /%postname%/ , we can find and redirect to the correct page.

For this we will add the following script in the file functions.php from the active WordPress theme:

add_action( 'template_redirect', 'maybe_redirect_404_old_permalink' );

function maybe_redirect_404_old_permalink() {
    // Only run this function if it's a 404 page
    if( ! is_404() ) {
        return;
    }
 
    // Trick to get the full URL
    $url = add_query_arg( '', '' );

    // We get the part referring to %postname%
    $parts = explode( '/', $url );
    $parts = array_filter( $parts );
    $size = count( $parts );
    $maybe_slug = $parts[ $size ] ;

    // We try to find the new link in the database
    $args = array(
        'name' => $maybe_slug,
        'post_type' => 'post',
        'post_status' => 'publish',
        'numberposts' => 1,
    );

    $posts = get_posts( $args );

    // We found the post
    if( $posts && ! empty( $posts[0] ->ID ) ) {
        $post_id = $posts[0] ->ID;

        $post_url = get_permalink( $post_id );

        // We redirect to the new URL with the permanent redirect status 301
        if( $post_url ) {
            wp_safe_redirect( $post_url, 301 );
        }
    }

  // If you get this far, it's because no posts were actually found
// and the 404 page will be displayed
}

Thanks to ben lobaugh , original creator of this solution!

0 0 votos
Nota do Artigo
Subscribe
Notify of
guest

0 Comentários
newest
oldest most voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x