mbis

Redirect old date-formatted post permalinks

Apr 4th, 2022 (edited)
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.11 KB | None | 0 0
  1. function bis_redirect_old_post_date_permalinks() {
  2.     global $wpdb, $wp;
  3.    
  4.     // 1. Run this function only if '404' error page was expected
  5.     if(!is_404() || empty($wp->request)) { return; }
  6.    
  7.     // 2. Check if requested URL matches the pattern (YYYY/MM/DD/post_slug)
  8.     preg_match('/^(20[\d]{2})\/([\d]{2})\/([\d]{2})\/([^\/]+)/', $wp->request, $parts);
  9.    
  10.     // 3. Execute rest of the code if the pattern was matched
  11.     if(!empty($parts[4])) {
  12.         $post_year = (int) $parts[1];
  13.         $post_month = (int) $parts[2];
  14.         $post_day = (int) $parts[3];
  15.         $post_slug = basename($parts[4]);
  16.        
  17.         $post = $wpdb->get_row($wpdb->prepare("
  18.             SELECT * FROM {$wpdb->posts}
  19.             WHERE post_name = %s
  20.             AND post_type = 'post'
  21.             AND YEAR(post_date) = %d
  22.             AND MONTH(post_date) = %d
  23.             AND DAY(post_date) = %d",
  24.             $post_slug,
  25.             $post_year,
  26.             $post_month,
  27.             $post_day
  28.         ));
  29.        
  30.         // Trigger the redirect if the post was found
  31.         if(!empty($post->ID)) {
  32.             $post_url = get_permalink($attachment->ID);
  33.             wp_safe_redirect($post_url, 301);
  34.             exit();
  35.         }
  36.     }
  37. }
  38. add_action('template_redirect', 'bis_redirect_old_post_date_permalinks');
Add Comment
Please, Sign In to add comment