Advertisement
Guest User

Redirect old slugs

a guest
Feb 2nd, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.87 KB | None | 0 0
  1. function pm_detect_old_slugs() {
  2.     global $wp_query, $wp, $wpdb;
  3.  
  4.     // Stop if any post or term was already found by Permalink Manager
  5.     if(!empty($wp_query->query['do_not_redirect']) || !empty($wp_query->query_vars['do_not_redirect']) || (!is_404())) {
  6.         return;
  7.     }
  8.  
  9.     // Get the string from URL
  10.     preg_match('/([^\/]+)(?:\/([\d]+))?/', $wp->request, $parts);
  11.     if(!empty($parts[1])) {
  12.         $post_id = $wpdb->get_var($wpdb->prepare("SELECT post_id from {$wpdb->postmeta} WHERE meta_key = '_wp_old_slug' AND meta_value LIKE '%%%s%%'", $parts[1]));
  13.  
  14.         // Redirect if post with old slug was found
  15.         if(!empty($post_id)) {
  16.             $permalink = get_permalink($post_id);
  17.             $permalink = (!empty($parts[2])) ? sprintf('%s/%d', trim($permalink, '/'), $parts[2]) : '';
  18.  
  19.             wp_safe_redirect($permalink, 301);
  20.             exit();
  21.         }
  22.     }
  23. }
  24. add_action('template_redirect', 'pm_detect_old_slugs', 0);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement