If you use Wordpress for managing your blog or CMS, then you know how it automatically generate the permalink of a post when you just provide the title of the post. It takes the Title, removes special characters or replaces them with a hyphen(-). Now, I was working on a project which required a news submission to Google news, for which I needed to fix an arbitrary 3 or more digit number to the permalink(Google requirement). So one way of doing that was to manually edit it each time i wrote a post. But that aint possible considering the frequency of posting. So I had to automate the process. So I looked around a bit, had a healthy conversation in StackOverflow but it didn't work well. So, when I was wandering around the post.php file, I noticed a function named wp_unique_post_slug() which seemed like the solution I needed! That function generates the slug of the post when the post title is passed to it. Here is the total function -
function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
	// A Whole Lot of Stuff is done here.. But what we really need is the final line ..
        // ....
        return $slug;
So, Just before the generated slug is returned from the function, I made the necessary changes. Like -
  $random=rand(11111,99999); //I needed 5 digit random
  $slug .= "-" . $random;
return $slug;
And Tada! My Job Done. So now if I give a post title like "Hello World", for a default Wordpress installation, the permalink generated would be - http://bibhas.in/blog/2010/12/hello-world/ but with my customization, I'd get a permalink like http://bibhas.in/blog/2010/12/hello-world-34523/ .. Where the number 34523 is a random number generated by my added code. :) So this way, you can make changes in your slug any way you want. But be careful when you edit the file. One mistake can literally Hang your blog. :P

Bibhas Debnath

iambibhas bibhasdn


blog comments powered by Disqus