I have created a post to posts relationship using ACF. On the single page of one of my CPTs I would like to add a prettified ID to the end of the slug to load different values on the page (/my-archive/my-single-post/ID) and have that ID saved to a query variable called custom_id. I also do not want the page to redirect to the original slug (/my-archive/my-single-post/).

I've managed to do the following:

add_action( 'init',  'add_custom_id_rewrite_rules' );
function add_custom_id_rewrite_rules() {
    add_rewrite_rule( '^my-archive/([^/]*)/([0-9]+)?$', 'index.php?post_type=my_post_type&pagename=$matches[1]&custom_id=$matches[2]', 'top' );

add_filter( 'query_vars', 'add_custom_id_query_vars' );
function add_custom_id_query_vars( $query_vars ) {
    $query_vars[] = 'custom_id';
    return $query_vars;

From everywhere I read, this should work. I've installed the Rewrite Rule Analyzer and it detects my custom_id correctly. However, despite it being considered correct I still get redirected to /my-archive/my-single-post/.

I want the query to still pull the_title() from that single post I just want to be able to query custom_id to change things on the page.


  • Unless I'm mistaken, your rule would conflict with post pagination (/my-archive/<post slug>/<page number>), i.e. single posts with that are split to multiple pages using the <!--nextpage--> tag. Why not just set the post type's rewrite slug to /my-archive/%postname%/%post_id%/ when you register your post type? Or you don't know how to do that? Can you show your post type registration code? Is my-archive actually a Page (post type page)?
    – Sally CJ
    Sep 2 at 13:33
  • my-archive is the slug given to the archive page of my CPT. I have a ton of records that I want to page so it's very possible that there's a conflict in rewrite rules but I've made sure to not have a conflict in the query variable names. I'm not familiar with the <!--nextpage--> tag and I'm not sure I understand what you mean by defining the rewrite slug to my posts. The individual posts are just fine, I just want to add my fake pages at the end of the slug without redirecting. Will any integer at the end of the URL conflict? I ask because I tried adding to the URL to distinguish the 2
    – Gazillion
    Sep 2 at 15:49
  • "Will any integer at the end of the URL conflict" - yes. More specifically, if the post has the <!--nextpage--> tag, e.g. Page 1<!--nextpage-->Page 2, then on page 2, WordPress won't recognize the page number because it became the value of the custom_id instead. See wp_link_pages() and the Page Break block.
    – Sally CJ
    Sep 2 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.