Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function bis_redirect_old_post_date_permalinks() {
- global $wpdb, $wp;
- // 1. Run this function only if '404' error page was expected
- if(!is_404() || empty($wp->request)) { return; }
- // 2. Check if requested URL matches the pattern (YYYY/MM/DD/post_slug)
- preg_match('/^(20[\d]{2})\/([\d]{2})\/([\d]{2})\/([^\/]+)/', $wp->request, $parts);
- // 3. Execute rest of the code if the pattern was matched
- if(!empty($parts[4])) {
- $post_year = (int) $parts[1];
- $post_month = (int) $parts[2];
- $post_day = (int) $parts[3];
- $post_slug = basename($parts[4]);
- $post = $wpdb->get_row($wpdb->prepare("
- SELECT * FROM {$wpdb->posts}
- WHERE post_name = %s
- AND post_type = 'post'
- AND YEAR(post_date) = %d
- AND MONTH(post_date) = %d
- AND DAY(post_date) = %d",
- $post_slug,
- $post_year,
- $post_month,
- $post_day
- ));
- // Trigger the redirect if the post was found
- if(!empty($post->ID)) {
- $post_url = get_permalink($attachment->ID);
- wp_safe_redirect($post_url, 301);
- exit();
- }
- }
- }
- add_action('template_redirect', 'bis_redirect_old_post_date_permalinks');
Add Comment
Please, Sign In to add comment