This one is a little more specific but let’s say you have a ton of posts that you need to rewrite their permalinks(slugs). To give you some idea of the situation that I had to use this for, when importing posts from Drupal to WordPress all of our posts that ended in “.html” were given a slug that ended in “-html”. This probably isn’t a common issue but you could use this code for other reasons too (add a custom field to the permalinks, switch dashes to underscores, remove small words, really your imagination can go wild here).

So let’s get into the code shall we:


$articles = get_posts(array('post_status' => 'publish'));
foreach($articles as $article) {
$oldslug = $article->post_name;
if ( substr($oldslug, -5) == "-html" ) {
$newslug = substr($oldslug,0, -5 );
$updatedarticle = array();
$updatearticle['ID'] = $article->ID;
$updatearticle['post_name'] = $newslug;
wp_update_post( $updatearticle );
echo $article->ID;
}
}

Now I had discovered wp_update_post when the problem first showed up but really couldn’t find a good way to use it, there seems to be a lot of issues with possible issue with creating an infinite loop so I was a little concerned with using it in a function. I broke down and simply made a #Page_Templates">page template and included the above code on the page.

So here is the break down of the code:


$articles = get_posts(array('post_status' => 'publish'));
foreach($articles as $article) {
$oldslug = $article->post_name;

The first part is pretty simple, I use get_posts to get all of the published posts and save the title to $oldslug = $article->post_name
The if statement:

if ( substr($oldslug, -5) == "-html" ) {
$newslug = substr($oldslug,0, -5 );

Is the a little more case specific code, basically I find all the post slugs that end in “-html” and assign $newslug the value of the old slug minus 5 characters (-html).


$updatedarticle = array();
$updatearticle['ID'] = $article->ID;
$updatearticle['post_name'] = $newslug;
wp_update_post( $updatearticle );
echo $article->ID;

Here is when we use wp_update_post to reassign the “post_name” (slug). I also echo the ID’s of the posts that were updated just to confirm that it worked.

So that is pretty much it. Like I said earlier, you can use this in many different ways, so let your imagination run wide.

Cheers!