Advertisement
mbis

Untitled

Jun 15th, 2022
1,024
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.42 KB | None | 0 0
  1. /**
  2.  * Detect posts
  3.  */
  4. function pm_detect_post_slugs($query) {
  5.     global $wpdb, $pm_query;
  6.    
  7.     // Do not run if custom permalink was detected
  8.     if(!empty($pm_query['id'])) {
  9.         return $query;
  10.     }
  11.    
  12.     // 1. Get the slug
  13.     if(!empty($query['pagename'])) {
  14.         $post_name = $query['pagename'];
  15.     } else if(!empty($query['name'])) {
  16.         $post_name = $query['name'];
  17.     } else if(!empty($query['attachment'])) {
  18.         $post_name = $query['attachment'];
  19.     }
  20.    
  21.     if(!empty($post_name)) {
  22.         $post_name = basename($post_name);
  23.        
  24.         // 2. Check if the slug is assigned to any post item
  25.         $sql_query = "SELECT post_name, post_type FROM $wpdb->posts WHERE 1=1 AND post_name = %s";
  26.         $post = $wpdb->get_row($wpdb->prepare($sql_query, array($post_name)));
  27.        
  28.         // 3. Filter the query if post was found
  29.         if(!empty($post->post_name)) {
  30.             $page = (!empty($query['page'])) ? $query['page'] : 1;
  31.             $new_query = array(
  32.                 'post_type' => $post->post_type,
  33.                 $post->post_type => $post->post_name,
  34.                 'page' => $page,
  35.                 'do_not_redirect' => 1,
  36.             );
  37.  
  38.             // 4. Disable canonical redirect
  39.             remove_action('template_redirect', 'wp_old_slug_redirect');
  40.             remove_action('template_redirect', 'redirect_canonical');
  41.             add_filter('wpml_is_redirected', '__return_false', 99, 2);
  42.             add_filter('pll_check_canonical_url', '__return_false', 99, 2);
  43.             return $new_query;
  44.         }
  45.     }
  46.     return $query;
  47. }
  48. add_filter('request', 'pm_detect_post_slugs', 9999);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement