Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Plugin Name: Post Slug as ID
- */
- add_filter('post_type_link', 'cpt_type_link', 1, 3);
- function cpt_type_link($url, $post = null, $leavename = false)
- {
- $tag = '%post_id%';
- if ($post->post_type != 'mycpt') {
- return $url;
- }
- $post_id = $post->ID;
- // replace tag with the slug: /youcpt/1234
- return str_replace($tag, $post_id, $url);
- }
- function cpt_add_rewrite_rules()
- {
- global $wp_rewrite;
- register_post_type('mycpt', array(
- 'name' => 'My Custom type',
- 'label' => 'Slug as ID',
- 'public' => true,
- 'has_archive' => true,
- 'rewrite' => array('slug' => 'products'),
- 'query_var' => true // ....
- )
- );
- $wp_rewrite->extra_permastructs['mycpt'][0] = "/products/%post_id%";
- add_rewrite_rule("products/?$", 'index.php?post_type=mycpt', 'top');
- add_rewrite_rule("products/([0-9]{1,})/?$", 'index.php?post_type=mycpt&p=$matches[1]', 'top');
- add_rewrite_rule("products/([0-9]{1,})/page/([0-9]{1,})/?$", 'index.php?post_type=mycpt&p=$matches[1]&paged=$matches[2]', 'bottom');
- flush_rewrite_rules(); // call just on plugin activation
- }
- add_action('init', 'cpt_add_rewrite_rules');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement