WordPress Rewrite URL

Been ripping my hair out trying to keep my blogpost links alive after porting to WP from flask… needed to transform my URLs to lower and swap underscores..

After a few overnights scrambling together code with no luck (I am behind nginx, and could prolly do it there).. but VX in #wordpress on freenode helped me out with this:

 

add_action( ‘wp’, ‘process_post’ );

function process_post($wp) {
$request = false;

if(preg_match(‘#^blogpost/\d+/(.*?)/?$#i’,$wp->request, $matches)) :
$request = str_replace( ‘_’, ‘-‘ , strtolower($matches[1]) );
elseif(preg_match(‘#^blogpost/(.*?)/?$#i’,$wp->request, $matches)) :
$request = str_replace( ‘_’, ‘-‘ , strtolower($matches[1]) );
endif;

if($request) :
wp_redirect( get_home_url() . ‘/’ . $request , ‘301’ );
exit;
endif;
}

Worked magic!!!

just put that in your theme’s functions.php and hack to work for you… (might not be the most performant/ best method, but it works!!!)

Leave a Reply

Your email address will not be published. Required fields are marked *