Advertisement
mbis

Detect old permalinks

Nov 6th, 2019 (edited)
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.01 KB | None | 0 0
  1. /**
  2.  * Detect old category permalinks
  3.  */
  4. function bis_detect_old_permalinks() {
  5.   global $wp, $wpdb;
  6.  
  7.   preg_match('/index.php(.*)?\/([^\/]+)/', trim($_SERVER['REQUEST_URI'], '/'), $parts);
  8.  
  9.   if(!empty($parts[2])) {
  10.         $slug = sanitize_text_field($parts[2]);
  11.  
  12.         // A. Check for term
  13.         $term = $wpdb->get_row($wpdb->prepare("SELECT t.slug, tt.taxonomy FROM $wpdb->terms AS t LEFT JOIN $wpdb->term_taxonomy AS tt ON (t.term_id = tt.term_id) WHERE slug = %s", $slug));
  14.  
  15.         if(!empty($term->slug)) {
  16.             $term_link = get_term_link($term->slug, $term->taxonomy);
  17.  
  18.             wp_safe_redirect($term_link, 301);
  19.             exit();
  20.         }
  21.  
  22.         // B. Check for post
  23.         $post = $wpdb->get_row($wpdb->prepare("SELECT ID, post_date FROM $wpdb->posts WHERE post_name = %s AND post_status = 'publish' ORDER BY post_date DESC", $slug));
  24.  
  25.         if(!empty($post->ID)) {
  26.             $post_link = get_permalink($post->ID);
  27.  
  28.             wp_safe_redirect($post_link, 301);
  29.             exit();
  30.         }
  31.   }
  32. }
  33. add_action('template_redirect', 'bis_detect_old_permalinks', 0);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement