SHARE
TWEET

Redirect old slugs

mbis Feb 14th, 2020 99 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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 all the endpoints & pattern
  10.     if(class_exists('Permalink_Manager_Helper_Functions')) {
  11.         $endpoints = Permalink_Manager_Helper_Functions::get_endpoints();
  12.         $pattern = "/^(.+?)(?|\/({$endpoints})(?|\/(.*)|$)|\/()([\d]+)\/?)?$/i";
  13.     } else {
  14.         $pattern = '/([^\/]+)?(?:\/([\d]+))?/';
  15.     }
  16.  
  17.     // Get the string from URL
  18.     preg_match($pattern, $wp->request, $parts);
  19.     if(!empty($parts[1])) {
  20.         $slug = basename($parts[1]);
  21.         $post_id = $wpdb->get_var($wpdb->prepare("SELECT post_id from {$wpdb->postmeta} WHERE meta_key = '_wp_old_slug' AND meta_value LIKE '%%%s%%'", $slug));
  22.  
  23.         // Parse the endpoints
  24.         $endpoint = (!empty($parts[2])) ? $parts[2] : '';
  25.         $endpoint_value = (!empty($parts[3])) ? $parts[3] : '';
  26.  
  27.         // Redirect if any post with old slug was found
  28.         if(!empty($post_id)) {
  29.             $permalink = get_permalink($post_id);
  30.  
  31.             if(!empty($endpoint_value) || !empty($endpoint)) {
  32.                 if(empty($endpoint) && is_numeric($endpoint_value)) {
  33.                     $permalink = sprintf("%s/%d", trim($permalink, "/"), $endpoint_value);
  34.                 } else if(isset($endpoint) && !empty($endpoint_value)) {
  35.                     $permalink = sprintf("%s/%s/%s", trim($permalink, "/"), $endpoint, $endpoint_value);
  36.                 } else {
  37.                     $permalink = sprintf("%s/%s", trim($permalink, "/"), $endpoint);
  38.                 }
  39.             }
  40.  
  41.             wp_safe_redirect($permalink, 301);
  42.             exit();
  43.         }
  44.     }
  45. }
  46. add_action('template_redirect', 'pm_detect_old_slugs', 0);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top