Advertisement
mbis

Make permalinks unique

Dec 16th, 2019
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.99 KB | None | 0 0
  1. /**
  2.  * Method 1. Force the unique custom permalinks
  3.  */
  4. function pm_force_unique_permalinks($uris) {
  5.     $duplicates = array_count_values($uris);
  6.  
  7.     foreach($duplicates as $uri => $count) {
  8.         if($count == 1) { continue; }
  9.  
  10.         $ids = array_keys($uris, $uri);
  11.  
  12.         foreach($ids as $index => $id) {
  13.             if($index > 0) {
  14.                 $uris[$id] = preg_replace('/(.+?)(\.[^\.]+$|$)/', '$1-' . $index . '$2', $uri);
  15.             }
  16.         }
  17.     }
  18.  
  19.     return $uris;
  20. }
  21. add_filter('permalink_manager_uris', 'pm_force_unique_permalinks', 10);
  22.  
  23. /**
  24.  * Method 2. Make the default permalinks unique
  25.  */
  26. function pm_make_uris_unique($default_uri, $original_slug, $element, $custom_slug, $native_uri) {
  27.     global $permalink_manager_uris;
  28.  
  29.     // if($native_uri ) { return $default_uri; }
  30.  
  31.     // Get the element ID
  32.     $element_id = (!empty($element->taxonomy)) ? "tax-{$element->term_taxonomy_id}" : $element->ID;
  33.  
  34.     // Check if the same URI was used for another post or term
  35.     $all_uris = $permalink_manager_uris;
  36.  
  37.     if(in_array($default_uri, $all_uris)) {
  38.         unset($all_uris[$element_id]);
  39.  
  40.         $duplicates = array_count_values($all_uris);
  41.         $duplicates_count = (isset($duplicates[$default_uri])) ? $duplicates[$default_uri] : 0;
  42.  
  43.         if($duplicates_count) {
  44.             $suffix = intval($duplicates_count) + 1;
  45.             $default_uri = preg_replace('/(.+?)(\.[^\.]+$|$)/', '$1-' . $suffix . '$2', $default_uri);
  46.         }
  47.     }
  48.  
  49.     return $default_uri;
  50. }
  51. add_filter('permalink_manager_filter_default_post_uri', 'pm_make_uris_unique', 99, 5);
  52. add_filter('permalink_manager_filter_default_term_uri', 'pm_make_uris_unique', 99, 5);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement