Advertisement
mbis

Unique permalinks

Jun 11th, 2020
950
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.29 KB | None | 0 0
  1. function pm_force_unique_permalinks($post_id, $new_uri, $old_uri) {
  2.     global $permalink_manager_uris;
  3.  
  4.     while(empty($new_unique_permalink)) {
  5.         $duplicates = array_keys($permalink_manager_uris, $new_uri);
  6.  
  7.         if(is_array($duplicates)) {
  8.             $duplicated_ids = array_flip($duplicates);
  9.  
  10.             // Ignore this particular post
  11.             if(isset($duplicated_ids[$post_id])) {
  12.                 unset($duplicated_ids[$post_id]);
  13.             }
  14.  
  15.             // Count duplicates
  16.             $duplicates_count = count($duplicated_ids) + 1;
  17.  
  18.             // Add numeral prefix to the URL
  19.             if($duplicates_count > 1) {
  20.                 preg_match('/(.*)-([\d]{1,3})$/', $new_uri, $out);
  21.                
  22.                 if(!empty($out[2])) {
  23.                     $new_uri = sprintf('%s-%d', $out[1], (int) $out[2] + 1);
  24.                 } else {
  25.                     $new_uri = preg_replace('/(.+?)(\.[^\.]+$|$)/', '$1-' . $duplicates_count . '$2', $new_uri);
  26.                 }
  27.             } else {
  28.                 $new_unique_permalink = $new_uri;
  29.             }
  30.         }
  31.     }
  32.  
  33.     $permalink_manager_uris[$post_id] = $new_unique_permalink;
  34.     update_option('permalink-manager-uris', $permalink_manager_uris);
  35. }
  36. // Make the new post's permalink unique
  37. add_action('permalink_manager_new_post_uri', 'pm_force_unique_permalinks', 10, 3);
  38.  
  39. // Make the existing permalink unique after the permalink is updated
  40. add_action('permalink_manager_updated_post_uri', 'pm_force_unique_permalinks', 10, 3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement