Custom post type URL with post ID that allows archiving and paging

Your code/solutions is pretty good. You use slug param in a very smart way, so WordPress automatically creates correct permastruct for this CPT.

The only thing you’re missing, I guess, is has_archive param. It’s default value is false and you don’t set it to true. So WordPress doesn’t create archive links/pages for your CPT.

has_archive (boolean or string)

(optional) Enables post type archives.

Will use $post_type as archive slug by default. Default: false Note:
Will generate the proper rewrite rules if rewrite is enabled. Also use
rewrite to change the slug used.

If you do this, WordPress will create rewrite rules for archive pages. There will be a tiny problem. They will contain %post_id% in them. But it’s pretty easy to correct. You just have to add this code after your register_post_type call:

global $wp_rewrite;

$new_rules = array();
foreach ( $wp_rewrite->extra_rules_top as $key => $rule ) {
    echo $key;
    if (strpos($key, 'post-type/%post_id%/') === 0 ) {
        $new_rules[ str_replace('%post_id%/', '', $key) ] = $rule;
        unset( $wp_rewrite->extra_rules_top[$key] );
    }
}
$wp_rewrite->extra_rules_top = $wp_rewrite->extra_rules_top + $new_rules;

It will repair rules for archive pages created by WordPress. It’s clean solution – it doesn’t leave any mess behind, and it takes care of all rules for archive page (feeds, etc.)

Leave a Comment