How to copy post titles to post slug in phpmyadmin

You do not want a simple SQL solution. post_name is used to generate permalinks. If you simply copy the title to the name (slug) you will have spaces and punctuation in the URL, and that is going to be a problem. It will result in broken links. Additionally, you could end up with two posts having the same permalink which will result in unpredictable behavior.

With SQL it should be possible to replace the spaces with dashes, and strip the punctuation, as WordPress does, but resolving the duplicate permalinks issue would be difficult in pure SQL. Let WordPress fix it. Place the following in functions.php and remove it after you fix the issue.

function fix_post_slugs() {
  $posts = new WP_Query(array('post_type'=>'book'));
  if (empty($posts->posts)) return false;
  foreach ($posts->posts as $p) {
    wp_update_post((array)$p);
  }
}
fix_post_slugs();

What you are doing is grabbing a post object and passing it back to wp_update_post as an array. All of the checks and balances run that would ordinarily sort out things like the slug. Of course, you will have to adjust the post type name to suit your install.

Tested, but barely. I would run this on a dummy database before trusting it with real data. I am fairly sure that this will do no damage, but paranoia is a virtue. Make backups first.

Leave a Comment