Regenerate All the Posts Slugs on WordPress

To start this process, enter the site with “regenerate_all_slugs” query string:

wpsiteurl.com?regenerate_all_slugs

if ( isset($_GET['regenerate_all_slugs']) ) {


    // get all posts
    $posts = get_posts( array('numberposts' => -1) );

    foreach ( $posts as $post ) {
        
        // check the slug and run an update if necessary 
        $old_slug = $post->post_name;
        $new_slug = sanitize_title( $post->post_title );

        if ( $post->post_name != $new_slug ) {
            wp_update_post(
                array (
                    'ID'        => $post->ID,
                    'post_name' => $new_slug
                )
            );
            echo "Regenerated: " . $old_slug . " -> " . $new_slug . " <br>";
        }

    }


}Code language: PHP (php)

Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.