Advertisement
luisabarca

Post Slug as ID

Oct 14th, 2011
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.24 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: Post Slug as ID
  4. */
  5.  
  6. add_filter('post_type_link', 'cpt_type_link', 1, 3);
  7.  
  8. function cpt_type_link($url, $post = null, $leavename = false)
  9. {
  10.     $tag = '%post_id%';
  11.  
  12.     if ($post->post_type != 'mycpt') {
  13.         return $url;
  14.     }
  15.    
  16.     $post_id = $post->ID;
  17.  
  18.     // replace tag with the slug: /youcpt/1234
  19.     return str_replace($tag, $post_id, $url);
  20. }
  21.  
  22.  
  23. function cpt_add_rewrite_rules()
  24. {
  25.     global $wp_rewrite;
  26.    
  27.     register_post_type('mycpt', array(
  28.         'name' => 'My Custom type',
  29.         'label' => 'Slug as ID',
  30.         'public' => true,
  31.         'has_archive' => true,
  32.         'rewrite' => array('slug' => 'products'),
  33.         'query_var' => true // ....
  34.         )
  35.     );
  36.    
  37.     $wp_rewrite->extra_permastructs['mycpt'][0] = "/products/%post_id%";
  38.  
  39.     add_rewrite_rule("products/?$", 'index.php?post_type=mycpt', 'top');
  40.     add_rewrite_rule("products/([0-9]{1,})/?$", 'index.php?post_type=mycpt&p=$matches[1]', 'top');
  41.     add_rewrite_rule("products/([0-9]{1,})/page/([0-9]{1,})/?$", 'index.php?post_type=mycpt&p=$matches[1]&paged=$matches[2]', 'bottom');    
  42.    
  43.     flush_rewrite_rules(); // call just on plugin activation
  44. }
  45.  
  46. add_action('init', 'cpt_add_rewrite_rules');
  47.  
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement