What’s the best way to ensure that post and page slugs use underscores instead of hyphens, without needing to edit the slug manually (or updating the page manually)
Current permalink:
www.<domain>.com/2011/05/this-is-a-test-post/
Desired permalink
www.<domain>.com/2011/05/this_is_a_test_post/
One approach I’ve tried is to hook into sanitize_title
, but this seems to only be called when the post is updated, so not very practical for a blog of several thousand post. Is there any way to force each post to update?
I need this to preserve compatibility as an old MovableType site is moved into WordPress – using .htaccess isn’t really an option
2 Answers
IMO hooking into sanitize_title is probably the best way to go here. Check out this plugin by Mark Jaquith which does something similar: http://txfx.net/files/wordpress/periods-in-titles.phps
As for updating the old posts, I would just write a simple script that would generate sql to manually update everything. (code not tested)
<?php
function sanitize_title_with_underscores( $title ) {
return str_replace( '-', '_', sanitize_title_with_dashes( $title ) );
}
$posts = get_posts( array( 'numberposts' => -1 ) );
foreach ( $posts as $post ) {
global $wpdb;
$id = absint( $post->ID );
$name = sanitize_title_with_underscores( $post->post_name );
print "\n" . "UPDATE $wpdb->posts SET post_name="{$name}" WHERE ID = {$id};"
}
?>
Probably not the most elegant solution, but for something that only needs to be done once, it should work rather well.