How to use add_rewrite_rule() for multi custom post types for same URL structure

I am developing a project in WordPress where I have 2 custom post types book and movie. The owner of this website wants me to make URL structure like the following:

Single book URL will be -> example.com/item/5565
Single movie URL will be -> example.com/item/6584

Where 5565 and 6584 are the post IDs.

So my client wants me to keep the URL structure of both post types same. I tried to use the following.

add_filter(‘post_type_link’, ‘wpse33551_post_type_link’, 1, 3);

function wpse33551_post_type_link( $link, $post = 0 ){
if ( $post->post_type == ‘book’ ){
return home_url( ‘item/’ . $post->ID );
} else {
return $link;
}
}

add_action( ‘init’, ‘wpse33551_rewrites_init’ );

function wpse33551_rewrites_init(){
add_rewrite_rule(
‘item/([0-9]+)?$’,
‘index.php?post_type=book&p=$matches[1]’,
‘top’ );
}

This approach works fine but only for one post type. It doesn’t work for both of the bost types at the same time.

My client is strict about to have the same URL structure.

So I need help to solve this problem. Any help will be appreciated.

Read more here:: How to use add_rewrite_rule() for multi custom post types for same URL structure

Leave a Reply

Your email address will not be published. Required fields are marked *