1

I have the following situation. I accidentally updated post_name column in wp_posts tables for all rows. Now I need to update those back somehow. I have researched that WP uses this function to generate slugs wp_unique_post_slug.

Can anyone please provide me with steps how to do this? I have no idea of PHP, plugins etc. What will I need to do this?

4

As @toscho already answered here, yes this is possible.

You just need to copy this code into the functions.php of your theme, and there you go.

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

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

    // use this line if you have multiple posts with the same title
    $new_slug = wp_unique_post_slug( $new_slug, $post->ID, $post->post_status, $post->post_type, $post->post_parent );

    if ( $post->post_name != $new_slug )
    {
        wp_update_post(
            array (
                'ID'        => $post->ID,
                'post_name' => $new_slug
            )
        );
    }
}

You can also create a plugin for that, if you create a yourplugin.php file in your plugins folder, with a valid plugin header and the above code:

<?php
    /*
    Plugin Name: Your Plugin
    Plugin URI: http://www.example.com
    Description: description
    Version: 0.1
    Author: thatsyou
    Author URI: http://www.yourdomain.com
    License: MIT
    */

    //yourcode
?>  

Please be aware that if you copy this code into your functions.php or your activate the plugin, it is executed all the time. You can get some ideas on how to execute code only once here: Best Practices

  • Hello! Thank you for the answer. Does wp_update_post internally call wp_unique_post_slug? – Giorgi Nakeuri Feb 20 '16 at 22:44
  • actually no. see updated answer. – fischi Feb 20 '16 at 22:55
  • Can we filter temporarily here $posts = get_posts( array ( 'numberposts' => -1 ) ); by specific ID so I can check it for one post first? – Giorgi Nakeuri Feb 20 '16 at 22:59
  • if you set numberposts to 1, not to -1, you only change one post. -1 means no limit. – fischi Feb 20 '16 at 23:04
  • No, no. I mean to filter it by post_id, not the first one. – Giorgi Nakeuri Feb 20 '16 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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