How to achieve permalink versatility

I am using a bit of custom code to list product categories in a permalink (Not ecommerce, just a product catalogue). The hierarchy is two product categories deep.

function my_product_post_link( $  post_link, $  id = 0 ){   $  post = get_post($  id);   if ( is_object( $  post ) ){     $  terms = wp_get_object_terms( $  post->ID, 'product-category' );     if( $  terms ){       if ( isset( $  terms[1] ) ) {         return str_replace( '%product-category%' , $  terms[0]->slug.'/'.$  terms[1]->slug , $  post_link );       } else {         return str_replace('%product-category%', $  terms[0]->slug, $  post_link);       }     }   }   return $  post_link; } add_filter( 'post_type_link', 'my_product_post_link', 1, 3 ); 

together with

'rewrite' => array('slug' => 'product/%product-category%/') 

in the CPT definition.

The problem is that a URL of mydomain.com/product/category1/category2/product_slug works fine but really I would also like mydomaim/product_slug to deliver the page, currently it’s a 404.

How would I achieve this? Before I started messing around either /product/product_slug or /product_slug would deliver the page so somehow I have broken this redirect capability.