Turn off %postname% auto-incrementing?

I use the permalink structure /%post_id%/%postname% because I have user submitted content. The problem is that %postname% still auto-increments itself and looks funny, even though the post id makes it unique. Is there a way to disable %postname% auto-incrementing?

domain.com/634/apple-pie
domain.com/635/apple-pie-2
domain.com/636/apple-pie-3

Read More

should be:

domain.com/634/apple-pie
domain.com/635/apple-pie
domain.com/636/apple-pie

Bonus points if you can do this just for a specified custom post type.

Related posts

Leave a Reply

2 comments

  1. Hi @Thompson:

    Unfortunately the post name must be unique for a given post type, and hierarchy level if the post type is hierarchical.

    There are a couple ways to address this:

    1. Use /%post_id%-%postname%/ instead of /%post_id%/%postname%/; that makes it unique and thus won’t append any annoying -Ns to the end of your URLs and will give you a slight improvement in SEO since the important keywords will be in the website root and not one directory level down. Or

    2. If you must have the URL structure you specify then you can just set your permalink to /%post_id%/ and use the 'post_link' and 'init' hooks to allow you to respectively append the post name onto the URL and to add a permastruct that matches a post_id, a slash, and anything after the slash but throws the latter two away because they are not used with the permalink structure:

    add_filter('post_link', 'mysite_post_link',10,2);
    function mysite_post_link($permalink,$post) {
      $post = get_post($post);
      return "{$permalink}{$post->post_name}/";
    }
    add_action('init', 'mysite_init');
    function mysite_init() {
      global $wp_rewrite;
      $wp_rewrite->add_permastruct("user_submitted_post",
        '%post_id%/.*?', 
        'p=matches[1]');
      $wp_rewrite->flush_rules();  // This line is only needed once
    }
    
  2. Try this:

    add_filter('wp_insert_post_data', 'remove_slug_suffix');
    
    function remove_slug_suffix($data) {
    
        if ('post' == $data['post_type'])
            $data['post_name'] = preg_replace('/-d+$/', '', $data['post_name']);
    
        return $data;
    }