Advertisement
mbis

Remove /product/ base

Nov 10th, 2019
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.47 KB | None | 0 0
  1. /**
  2.  * Detect product permalinks
  3.  */
  4. function pm_detect_post_slugs($query) {
  5.     global $wpdb, $pm_query;
  6.  
  7.     if(!empty($pm_query['uri'])) {
  8.         $post_name = basename($pm_query['uri']);
  9.  
  10.         $sql_query = $wpdb->prepare(
  11.             "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = 'product'",
  12.             array($post_name)
  13.         );
  14.         $uri = $wpdb->get_var($sql_query);
  15.  
  16.         if(!empty($uri)) {
  17.             $page = (!empty($query['page'])) ? $query['page'] : 1;
  18.             $new_query = array(
  19.                 'product' => $uri,
  20.                 'post_type' => 'product',
  21.                 'name' => $uri,
  22.                 'page' => $page,
  23.                 'do_not_redirect' => 1,
  24.             );
  25.  
  26.             // Disable canonical redirect
  27.             remove_action('template_redirect', 'wp_old_slug_redirect');
  28.             remove_action('template_redirect', 'redirect_canonical');
  29.             add_filter('wpml_is_redirected', '__return_false', 99, 2);
  30.             add_filter('pll_check_canonical_url', '__return_false', 99, 2);
  31.  
  32.             return $new_query;
  33.         }
  34.     }
  35.  
  36.     return $query;
  37. }
  38. add_filter('request', 'pm_detect_post_slugs');
  39.  
  40. /**
  41. * Filter product permalinks
  42. */
  43. function bis_filter_product_permalinks($url, $element) {
  44.     if(!empty($element->post_type) && ($element->post_type == 'product')) {
  45.         $home_base = trim(get_option('home'), '/');
  46.        
  47.         // $url = preg_replace('/(http(?:s)?:\/\/(?:www\.)?[^\/]+\/)([^\/]+)\/([^\/]+)/', '$1$3', $url);
  48.         $url = "{$home_base}/{$element->post_name}";
  49.     }
  50.  
  51.     return user_trailingslashit($url);
  52. }
  53. add_filter('post_type_link', 'bis_filter_product_permalinks', 999, 2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement