Check if posts lives somewhere else when old permalink triggers 404
-
Hiya,
Here’s what I want to do:
1. A user accesses my blog through an old permalink
2. The system can’t find the post/page
3. I grab the post slug form the requested path
4. I search wp_posts WHERE post_name = ‘$slug’
5. If I get a result, I present a 301 Moved Permanently header with the right path, if not I present a 404 error.I know there’s several ways to migrate permalink structures, but in this case there’s no clear format in the permalink that were used, so this is by far the most efficient way.
I have managed to do this by hacking /wp-includes/classes.php:
// BEGIN: check if document exists somewhere else $parts = explode("/", $_SERVER['REQUEST_URI']); if( preg_match("/\/$/", $_SERVER['REQUEST_URI'] ) ) { $slug = addslashes( $parts[ (sizeof($parts)-2) ] ); } else { $slug = addslashes( $parts[ (sizeof($parts)-1) ] ); } global $wpdb; if( $guid = $wpdb->get_var( "SELECT guid FROM wp_posts WHERE post_name = '" . $slug . "'" ) ) { header( "HTTP/1.1 301 Moved Permanently" ); header( "Location: $guid" ); } else { $wp_query->set_404(); status_header( 404 ); nocache_headers(); } // END: check if document exists somewhere else
However, I obviously would rather do this in the shape of a plugin.
Does anyone have any suggestions of how to trigger this process from a plugin, using a specific hook for instance? Or perhaps another solution I haven’t thought about?
Thanks in advance.
- The topic ‘Check if posts lives somewhere else when old permalink triggers 404’ is closed to new replies.