0

is there a way to have multiple permalinks for a custom post type post?

For example:

The normal permalink url is called:

https://www.example.com/test-subject/test-title

I also want the post is reachable under the following urls:

https://www.example.com/test-subject/post_id

https://www.example.com/ts/post_id

I know that I can manual add in the .htaccess, but I add the post inside my plugin. So what is the best method to add these urls to a post and make them accessable?

I need some suggestions, not code solution.

1 Answer 1

1

Yes this is possible using add_rewrite_rule(), something along the lines of

add_rewrite_rule(
    'test-subject/(\d+)/?',
    'index.php?post_type=CPT_slug&post_id=$matches[1]'
);
add_rewrite_rule(
    'ts/(\d+)/?',
    'index.php?post_type=CPT_slug&post_id=$matches[1]'
);

It might be a bit trickier though, since test-subject/test-title and test-subject/post_id are quite similar. Adding the post_id-rule with the 3rd argument as 'top' might help.

5
  • I added in the main file of my plugin . function add_my_rule() { add_rewrite_rule( 'test-subject/(\d+)/?', 'index.php?post_type=real_estate&page_id=$matches[1]' ); } add_action('init', 'add_my_rule'); is not working
    – yfain
    Jul 4, 2018 at 8:45
  • It works, redirects to a different page as the original. Maybe there is a solution with a specific meta_key & meta_value?
    – yfain
    Jul 4, 2018 at 8:49
  • You need to flush the rewrite rules after first adding the code. I don't have much time right now to help further, maybe page_id is the wrong key (although it worked in my small test)?
    – kero
    Jul 4, 2018 at 8:56
  • 1
    OK, worked. I used index.php?p=post_id
    – yfain
    Jul 4, 2018 at 9:00
  • @yfain Thanks for the updated, I changed my answer so other people will have the correct answer straight away
    – kero
    Jul 4, 2018 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.