• There was a closed thread about this same topic by Ne0Que. I wanted to add my word to it.

    All the solutions presented here were giving a Page Not found error. But this code worked for me. The extra things I did
    – swapped the cpt_id and postname
    – added one mroe add_rewrite_tag for custompostname

    Remember to:
    – replace custompostname, customposts with yours
    – flush rewriterules by visiting the permalinks page once.

    Here is the code I put in functions.php

    add_action('init', 'customposts_rewrite');
    function customposts_rewrite() {
      global $wp_rewrite;
      $wp_rewrite->add_rewrite_tag('%cpt_id%', '([^/]+)', "cpt_id=");
      $wp_rewrite->add_rewrite_tag('%custompostname%', '([^/]+)', "custompostname=");
      $wp_rewrite->add_permastruct('customposts', '/customposts/%custompostname%/%cpt_id%/', false);
    }
    
    add_filter('post_type_link', 'customposts_permalink', 1, 3);
    function customposts_permalink($post_link, $id=0, $leavename, $sample) {
      global $wp_rewrite;
      $post = &get_post($id);
      if ( is_wp_error( $post ) )
        return $post;
      $post_link = $wp_rewrite->get_extra_permastruct('customposts');
      $post_link = str_replace("%cpt_id%", $post->ID, $post_link);
      $post_link = str_replace("%custompostname%", $post->post_name, $post_link);
      $post_link = home_url(user_trailingslashit($post_link));
      return $post_link;
    }

    Hope this helps others.
    Am able to get this structure in the URL and all these work:
    domain.com/customposttype/custompostname/cpt_id/
    domain.com/blog/postname/

    Shiva

  • The topic ‘custom post type with post_id in permalink structure’ is closed to new replies.